阶段六:完成生成契约迁移并永久关闭旁路

This commit is contained in:
Christ committed 2026-08-20 03:48:33 +08:00
1 parent 5675f60e52
commit 76f4e2e87d
117 files changed
+5833 -2204

No files matched your search

+1 -1
View File
@@ -89,7 +89,7 @@ func TestChatWebSocketStreamsOnlyAuthenticatedAccountEvents(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
defer cancel()
// conn、err 用于本次流程后续判断的conn、err
conn, _, err := websocket.Dial(ctx, "ws"+strings.TrimPrefix(httpServer.URL, "http")+"/api/chat/ws", &websocket.DialOptions{HTTPHeader: header})
conn, _, err := websocket.Dial(ctx, "ws"+strings.TrimPrefix(httpServer.URL, "http")+"/api/v1/chat/ws", &websocket.DialOptions{HTTPHeader: header})
if err != nil {
t.Fatal(err)
}
@@ -0,0 +1,332 @@
package server
import (
"bytes"
"context"
"encoding/json"
"fmt"
"mime/multipart"
"net/http"
"net/http/httptest"
"net/url"
"path/filepath"
"sort"
"strconv"
"strings"
"testing"
"github.com/getkin/kin-openapi/openapi3"
)
// TestOpenAPIOperationsHaveContractScenarios 从 OpenAPI operationId 自动生成最小请求,确保每个版本化 operation 都经过真实 Router 响应契约校验。
func TestOpenAPIOperationsHaveContractScenarios(t *testing.T) {
// document 是唯一 OpenAPI 契约源的解析结果。
document := loadOpenAPIContractForCoverage(t)
// operations 保存按路径和方法排序后的全部版本化 operation 场景。
operations := collectOpenAPIOperations(document)
// operation 表示当前规范枚举的 operation 场景,副本用于闭包隔离。
for _, operation := range operations {
// operation 是由 OpenAPI 文档直接枚举的当前测试场景,不允许手工名单遗漏。
operation := operation
t.Run(operation.operation.OperationID, func(t *testing.T) {
// srv、_、cleanup 分别是当前 operation 独占的真实 Server、测试数据库和资源释放函数。
srv, _, cleanup := newTestServer(t)
defer cleanup()
// handler 是当前 operation 使用的完整 chi Router。
handler := srv.Router()
// sessionCookie 是当前 operation 独占的管理员会话,避免删除或登出影响其他场景。
sessionCookie := loginHelper(t, handler)
// request 是根据路径参数、必需查询参数和请求体 schema 生成的最小真实请求。
request := newOpenAPICoverageRequest(t, operation.path, operation.method, operation.operation)
request.AddCookie(sessionCookie)
// recorder 捕获真实 Router 对当前 operation 的状态、响应头和响应体。
recorder := httptest.NewRecorder()
handler.ServeHTTP(recorder, request)
assertOpenAPIResponse(t, request, recorder)
})
}
}
// openAPICoverageOperation 保存一个由 OpenAPI 路径、方法和 operationId 构成的自动测试场景。
type openAPICoverageOperation struct {
// key 是方法和路径组成的稳定场景键。
key string
// path 是 OpenAPI 路径模板。
path string
// method 是小写 HTTP 方法。
method string
// operation 是当前 operation 的完整契约定义。
operation *openapi3.Operation
}
// loadOpenAPIContractForCoverage 加载并校验自动 operation 覆盖测试使用的契约文档。
func loadOpenAPIContractForCoverage(t *testing.T) *openapi3.T {
t.Helper()
// specPath 是从 Server 测试目录定位到唯一 OpenAPI 契约源的路径。
specPath := filepath.Join("..", "..", "api", "openapi.yaml")
// document、loadErr 分别是解析后的契约文档和加载失败原因。
document, loadErr := openapi3.NewLoader().LoadFromFile(specPath)
if loadErr != nil {
t.Fatalf("加载 OpenAPI 契约失败: %v", loadErr)
}
// validationErr 表示契约未满足 OpenAPI 语义约束的原因。
if validationErr := document.Validate(context.Background()); validationErr != nil {
t.Fatalf("OpenAPI 契约无效: %v", validationErr)
}
return document
}
// collectOpenAPIOperations 从规范自动收集全部版本化 operation,不维护独立路径或 DTO 名单。
func collectOpenAPIOperations(document *openapi3.T) []openAPICoverageOperation {
// operations 保存待运行的所有 OpenAPI operation 场景。
operations := make([]openAPICoverageOperation, 0)
// path 表示 OpenAPI 中登记的 HTTP 路径模板。
for _, path := range document.Paths.Keys() {
// pathItem 是当前路径模板的 operation 集合。
pathItem := document.Paths.Find(path)
// method 表示当前路径登记的 HTTP 动词;operation 表示其契约定义。
for method, operation := range pathItem.Operations() {
// normalizedMethod 是用于排序和构造请求的标准小写方法。
normalizedMethod := strings.ToLower(method)
operations = append(operations, openAPICoverageOperation{
key: normalizedMethod + " " + path,
path: path,
method: normalizedMethod,
operation: operation,
})
}
}
sort.Slice(operations, func(left, right int) bool {
// left、right 是待比较的场景下标,排序保证失败输出稳定。
return operations[left].key < operations[right].key
})
return operations
}
// newOpenAPICoverageRequest 根据 operation 的参数和请求体 schema 生成真实 HTTP 请求。
func newOpenAPICoverageRequest(t *testing.T, path string, method string, operation *openapi3.Operation) *http.Request {
t.Helper()
// resolvedPath 是将 OpenAPI 路径参数替换为可解析占位值后的 URL 路径。
resolvedPath := path
// parameter 表示当前 operation 的路径参数定义。
for _, parameter := range operation.Parameters {
// parameterValue 是当前路径或查询参数的最小稳定值。
if parameter.Value == nil || parameter.Value.In != "path" {
continue
}
resolvedPath = strings.ReplaceAll(resolvedPath, "{"+parameter.Value.Name+"}", openAPIParameterValue(parameter.Value.Name, parameter.Value.Schema))
}
// queryValues 保存规范声明的必需查询参数,避免自动场景依赖手工路径列表。
queryValues := url.Values{}
// parameter 表示当前 operation 的查询参数定义。
for _, parameter := range operation.Parameters {
// parameterValue 是当前参数引用解析后的值。
parameterValue := parameter.Value
if parameterValue == nil || parameterValue.In != "query" || !parameterValue.Required {
continue
}
queryValues.Set(parameterValue.Name, openAPIParameterValue(parameterValue.Name, parameterValue.Schema))
}
// encodedQuery 是将必需查询参数按 URL 规则编码后的字符串。
if encodedQuery := queryValues.Encode(); encodedQuery != "" {
resolvedPath += "?" + encodedQuery
}
// body、contentType 分别是按请求体 schema 生成的载荷和媒体类型。
body, contentType := openAPICoverageRequestBody(t, operation.RequestBody)
// request 是供真实 chi Router 执行的最小 HTTP 请求。
request := httptest.NewRequest(strings.ToUpper(method), resolvedPath, bytes.NewReader(body))
if contentType != "" {
request.Header.Set("Content-Type", contentType)
}
return request
}
// openAPICoverageRequestBody 按 OpenAPI 请求体媒体类型生成 JSON 或 multipart 载荷。
func openAPICoverageRequestBody(t *testing.T, requestBody *openapi3.RequestBodyRef) ([]byte, string) {
t.Helper()
if requestBody == nil || requestBody.Value == nil || len(requestBody.Value.Content) == 0 {
return nil, ""
}
// mediaType 是优先选择 JSON、其次 multipart、最后按稳定顺序选择的请求媒体类型。
mediaType := ""
// candidate 表示请求体支持的一种媒体类型。
for candidate := range requestBody.Value.Content {
if candidate == "application/json" {
mediaType = candidate
break
}
if mediaType == "" && strings.HasPrefix(candidate, "multipart/") {
mediaType = candidate
}
if mediaType == "" {
mediaType = candidate
}
}
if strings.HasPrefix(mediaType, "multipart/") {
// buffer、writer 分别保存 multipart 请求体和字段编码器。
buffer := &bytes.Buffer{}
// writer 负责以边界格式编码最小 multipart 请求体。
writer := multipart.NewWriter(buffer)
// closeErr 表示 multipart 编码器关闭并写入结尾边界时的错误。
if closeErr := writer.Close(); closeErr != nil {
t.Fatalf("生成 multipart 契约请求失败: %v", closeErr)
}
return buffer.Bytes(), writer.FormDataContentType()
}
// mediaSchema 是当前媒体类型声明的 JSON schema。
mediaSchema := requestBody.Value.Content[mediaType]
if mediaSchema == nil || mediaSchema.Schema == nil {
return []byte("{}"), mediaType
}
// payload 是依据 schema 已知字段递归生成的 JSON 值,主动覆盖可选输入字段的类型约束。
payload := openAPICoverageRequestValue(mediaSchema.Schema)
// encoded、marshalErr 分别是 JSON 请求体和编码失败原因。
encoded, marshalErr := json.Marshal(payload)
if marshalErr != nil {
t.Fatalf("生成 JSON 契约请求失败: %v", marshalErr)
}
return encoded, mediaType
}
// openAPICoverageRequestValue 按请求 schema 生成包含全部已知属性的最小 JSON 值,避免可选 DTO 字段遗漏长期未被调用。
func openAPICoverageRequestValue(schemaRef *openapi3.SchemaRef) any {
if schemaRef == nil || schemaRef.Value == nil {
return nil
}
// schema 是当前递归层的具体请求 schema 定义。
schema := schemaRef.Value
if schema.Example != nil || schema.Default != nil || schema.Const != nil || len(schema.Enum) > 0 || len(schema.OneOf) > 0 || len(schema.AnyOf) > 0 {
return openAPICoverageValue(schemaRef)
}
if schema.Type == nil || len(*schema.Type) == 0 || (*schema.Type)[0] != "object" {
return openAPICoverageValue(schemaRef)
}
// propertyNames 保存按字典序生成的已知请求字段,保证失败输出和负载稳定。
propertyNames := make([]string, 0, len(schema.Properties))
// propertyName 表示当前 schema 中发现的请求属性名称。
for propertyName := range schema.Properties {
propertyNames = append(propertyNames, propertyName)
}
sort.Strings(propertyNames)
// objectValue 保存所有已声明请求字段的递归最小值。
objectValue := make(map[string]any, len(propertyNames))
// propertyName 表示当前需要编码到请求 JSON 中的 schema 属性名称。
for _, propertyName := range propertyNames {
// property 是当前请求字段的类型约束。
property := schema.Properties[propertyName]
objectValue[propertyName] = openAPICoverageRequestValue(property)
}
return objectValue
}
// openAPICoverageValue 按 schema 生成满足结构约束的最小 JSON 值。
func openAPICoverageValue(schemaRef *openapi3.SchemaRef) any {
if schemaRef == nil || schemaRef.Value == nil {
return nil
}
// schema 是当前递归层的具体 schema 定义。
schema := schemaRef.Value
if schema.Example != nil {
return schema.Example
}
if schema.Default != nil {
return schema.Default
}
if schema.Const != nil {
return schema.Const
}
if len(schema.Enum) > 0 {
return schema.Enum[0]
}
if len(schema.OneOf) > 0 {
return openAPICoverageValue(schema.OneOf[0])
}
if len(schema.AnyOf) > 0 {
return openAPICoverageValue(schema.AnyOf[0])
}
// schemaType 是当前 schema 的首个声明类型。
schemaType := ""
if schema.Type != nil && len(*schema.Type) > 0 {
schemaType = (*schema.Type)[0]
}
switch schemaType {
case "object":
// objectValue 保存对象必需字段的递归结果。
objectValue := make(map[string]any, len(schema.Required))
// requiredName 表示当前对象必须生成的字段名称。
for _, requiredName := range schema.Required {
// property 是必需字段的 schema 定义。
property := schema.Properties[requiredName]
objectValue[requiredName] = openAPICoverageValue(property)
}
return objectValue
case "array":
if schema.Items == nil {
return []any{}
}
if schema.MinItems > 0 {
return []any{openAPICoverageValue(schema.Items)}
}
return []any{}
case "integer":
if schema.Min != nil {
return int64(*schema.Min)
}
return int64(1)
case "number":
if schema.Min != nil {
return *schema.Min
}
return float64(1)
case "boolean":
return true
default:
if schema.Format == "date-time" {
return "2026-01-01T00:00:00Z"
}
return "contract-test"
}
}
// openAPIParameterValue 依据参数名称和 schema 生成可被 handler 解析的路径或查询值。
func openAPIParameterValue(name string, schemaRef *openapi3.SchemaRef) string {
// normalizedName 是便于判断业务语义的参数名称。
normalizedName := strings.ToLower(name)
switch {
case strings.Contains(normalizedName, "user_id"), strings.Contains(normalizedName, "card_id"), strings.Contains(normalizedName, "channel_id"):
return "999999"
case strings.Contains(normalizedName, "index"):
return "0"
case strings.Contains(normalizedName, "cookie"), strings.HasSuffix(normalizedName, "cid"), strings.Contains(normalizedName, "account"):
return "acc1"
case strings.Contains(normalizedName, "order"):
return "missing-order"
case strings.Contains(normalizedName, "session"):
return "missing-session"
case strings.Contains(normalizedName, "batch"):
return "missing-batch"
case strings.Contains(normalizedName, "job"):
return "missing-job"
case strings.Contains(normalizedName, "task"), strings.Contains(normalizedName, "run"), strings.Contains(normalizedName, "rule"):
return "missing-resource"
case strings.Contains(normalizedName, "item"):
return "missing-item"
case normalizedName == "key":
return "theme_color"
}
// value 是没有业务名称提示时按 schema 生成的通用参数值。
value := openAPICoverageValue(schemaRef)
// typedValue 是按 OpenAPI 参数 schema 生成的具体基础类型值。
switch typedValue := value.(type) {
case string:
return typedValue
case bool:
return strconv.FormatBool(typedValue)
case int64:
return strconv.FormatInt(typedValue, 10)
case float64:
return strconv.FormatFloat(typedValue, 'f', -1, 64)
default:
return fmt.Sprint(typedValue)
}
}
@@ -0,0 +1,782 @@
package server
import (
"bytes"
"context"
"encoding/json"
"io"
"mime/multipart"
"net/http"
"net/http/httptest"
"net/textproto"
"strconv"
"strings"
"testing"
"time"
automationapp "xianyu-go/internal/application/automation"
chatapp "xianyu-go/internal/application/chat"
itemapp "xianyu-go/internal/application/items"
notificationsapp "xianyu-go/internal/application/notifications"
"xianyu-go/internal/db"
"xianyu-go/internal/xianyu/cookierefresh"
"xianyu-go/internal/xianyu/mtop"
xrenew "xianyu-go/internal/xianyu/renew"
)
// TestOpenAPIRemainingVersionedSuccessResponses 验证仍未被既有兼容测试触达的版本化本地成功响应。
func TestOpenAPIRemainingVersionedSuccessResponses(t *testing.T) {
// t.Run 将相互独立的真实 Router 场景隔离,避免各自的数据库状态互相影响。
t.Run("initialize", testOpenAPISessionInitializeSuccess)
t.Run("long-login", testOpenAPILongLoginSuccess)
t.Run("ai-models", testOpenAPIAIModelsSuccess)
t.Run("cards-batch", testOpenAPICardsBatchSuccess)
t.Run("chat-history-and-read", testOpenAPIChatHistoryAndReadSuccess)
t.Run("local-item-and-manual-ship", testOpenAPILocalItemAndManualShipSuccess)
t.Run("category-recommendation", testOpenAPIItemCategoryRecommendationSuccess)
t.Run("publish-batch-preview", testOpenAPIPublishBatchPreviewSuccess)
t.Run("uncertain-notifications", testOpenAPIUncertainNotificationSuccess)
t.Run("chat-send", testOpenAPIChatSendSuccess)
t.Run("item-sync", testOpenAPIItemSyncSuccess)
t.Run("item-publish", testOpenAPIItemPublishSuccess)
t.Run("batch-lifecycle", testOpenAPIBatchLifecycleSuccess)
t.Run("automation-resolve", testOpenAPIAutomationResolveSuccess)
t.Run("notification-test", testOpenAPINotificationChannelTestSuccess)
t.Run("account-task-run", testOpenAPIAccountTaskRunSuccess)
}
// testOpenAPISessionInitializeSuccess 覆盖首次初始化的真实公开成功响应。
func testOpenAPISessionInitializeSuccess(t *testing.T) {
// srv、_、cleanup 分别是未初始化服务、当前场景无需读取的存储和资源释放函数。
srv, _, cleanup := newUninitializedTestServer(t)
defer cleanup()
// handler 是未经包装的真实 Router,初始化会在响应中写入会话 Cookie。
handler := srv.Router()
// request 是提交首次管理员密码的版本化初始化请求。
request := httptest.NewRequest(http.MethodPost, "/api/v1/session/initialize", strings.NewReader(`{"password":"initial-password"}`))
request.Header.Set("Content-Type", "application/json")
// recorder 保存真实 handler 返回的状态、响应头和响应体。
recorder := httptest.NewRecorder()
handler.ServeHTTP(recorder, request)
assertOpenAPIRecordedSuccessResponse(t, request, recorder)
}
// testOpenAPILongLoginSuccess 覆盖长登录读取和开关更新的真实平台代理成功响应。
func testOpenAPILongLoginSuccess(t *testing.T) {
// passport 是本地续期服务替身,仅提供真实 handler 所需的平台协议响应。
passport := httptest.NewServer(http.HandlerFunc(func(responseWriter http.ResponseWriter, request *http.Request) {
// responseWriter、request 分别承载本地平台替身的响应和请求。
responseWriter.Header().Add("Set-Cookie", "havana_lgc_exp=4102444800000; Domain=.goofish.com; Path=/; Secure")
if strings.Contains(request.URL.Path, "set") {
_, _ = responseWriter.Write([]byte(`{"data":{"success":true}}`))
return
}
_, _ = responseWriter.Write([]byte(`{"content":{"data":{"returnValue":{"canOpenLongLogin":true,"hasLongTokenLogin":true}}}}`))
}))
defer passport.Close()
// srv、store、cleanup 分别是服务、用于准备浏览器 Cookie 快照的存储和资源释放函数。
srv, store, cleanup := newTestServer(t)
defer cleanup()
setTestCookieRenew(srv, xrenew.Service{HTTPClient: passport.Client(), QueryLoginSettingsURL: passport.URL + "/query", SetLoginSettingsURL: passport.URL + "/set"})
// detail、detailErr 保存当前账号的加密凭证详情及读取错误。
detail, detailErr := store.Cookies.GetDetails(context.Background(), "acc1")
if detailErr != nil {
t.Fatalf("读取长登录账号失败: %v", detailErr)
}
// metadata 保存带域名快照的凭证元数据,使真实续期适配器可调用本地平台替身。
metadata := cookierefresh.MetadataWithSnapshot(detail.MetadataJSON, cookierefresh.SnapshotFromCookieString(detail.Value, ".goofish.com"))
// updateErr 表示写入测试长登录 Cookie 快照失败。
if updateErr := store.Cookies.UpdateRenewalCookie(context.Background(), "acc1", detail.Value, metadata, time.Now().Unix()); updateErr != nil {
t.Fatalf("准备长登录凭证快照失败: %v", updateErr)
}
// handler 是当前场景使用的真实版本化 Router。
handler := srv.Router()
// sessionCookie 是管理员认证会话。
sessionCookie := loginHelper(t, handler)
// requests 保存读取与写入长登录状态的两个版本化成功请求。
requests := []*http.Request{
httptest.NewRequest(http.MethodGet, "/api/v1/accounts/acc1/long-login", nil),
httptest.NewRequest(http.MethodPut, "/api/v1/accounts/acc1/long-login", strings.NewReader(`{"enabled":true}`)),
}
// request 是当前真实长登录请求。
for _, request := range requests {
request.Header.Set("Content-Type", "application/json")
request.AddCookie(sessionCookie)
// recorder 保存当前请求的完整真实响应。
recorder := httptest.NewRecorder()
handler.ServeHTTP(recorder, request)
assertOpenAPIRecordedSuccessResponse(t, request, recorder)
}
}
// testOpenAPIAIModelsSuccess 覆盖 AI 模型代理的本地成功响应。
func testOpenAPIAIModelsSuccess(t *testing.T) {
// modelServer 模拟兼容 OpenAI 的模型列表端点。
modelServer := httptest.NewServer(http.HandlerFunc(func(responseWriter http.ResponseWriter, request *http.Request) {
// responseWriter、request 分别承载模型替身响应和请求;请求内容无需在本场景读取。
responseWriter.Header().Set("Content-Type", "application/json")
_, _ = responseWriter.Write([]byte(`{"data":[{"id":"contract-model"}]}`))
}))
defer modelServer.Close()
// srv、_、cleanup 分别是服务、无需直接读取的存储和资源释放函数。
srv, _, cleanup := newTestServer(t)
defer cleanup()
// handler 是当前场景的真实 Router。
handler := srv.Router()
// sessionCookie 是访问管理员模型代理所需的认证会话。
sessionCookie := loginHelper(t, handler)
// request 是指向本地模型替身的版本化 AI 模型请求。
request := httptest.NewRequest(http.MethodPost, "/api/v1/settings/ai-models", strings.NewReader(`{"base_url":"`+modelServer.URL+`","api_key":"test-key"}`))
request.Header.Set("Content-Type", "application/json")
request.AddCookie(sessionCookie)
// recorder 保存真实代理成功响应。
recorder := httptest.NewRecorder()
handler.ServeHTTP(recorder, request)
assertOpenAPIRecordedSuccessResponse(t, request, recorder)
}
// testOpenAPICardsBatchSuccess 覆盖卡券 CSV 上传的真实 multipart 成功响应。
func testOpenAPICardsBatchSuccess(t *testing.T) {
// srv、_、cleanup 分别是服务、无需直接读取的存储和资源释放函数。
srv, _, cleanup := newTestServer(t)
defer cleanup()
// handler 是当前场景的真实 Router。
handler := srv.Router()
// sessionCookie 是当前管理员认证会话。
sessionCookie := loginHelper(t, handler)
// body 保存上传 CSV 的 multipart 编码结果。
var body bytes.Buffer
// writer 负责组装符合真实 handler 预期的 multipart 请求。
writer := multipart.NewWriter(&body)
// file、fileErr 分别是 CSV 表单文件写入器及创建失败原因。
file, fileErr := writer.CreateFormFile("file", "cards.csv")
if fileErr != nil {
t.Fatalf("创建卡券表单文件失败: %v", fileErr)
}
// writeErr 表示写入测试卡券 CSV 内容失败。
if _, writeErr := io.WriteString(file, "name,type,content\n合同卡,text,serial-001\n"); writeErr != nil {
t.Fatalf("写入卡券 CSV 失败: %v", writeErr)
}
// closeErr 表示完成卡券 multipart 编码失败。
if closeErr := writer.Close(); closeErr != nil {
t.Fatalf("关闭卡券 multipart 失败: %v", closeErr)
}
// request 是真实卡券批量上传请求。
request := httptest.NewRequest(http.MethodPost, "/api/v1/cards/batch", &body)
request.Header.Set("Content-Type", writer.FormDataContentType())
request.AddCookie(sessionCookie)
// recorder 保存批量创建的真实成功响应。
recorder := httptest.NewRecorder()
handler.ServeHTTP(recorder, request)
assertOpenAPIRecordedSuccessResponse(t, request, recorder)
}
// testOpenAPIChatHistoryAndReadSuccess 覆盖聊天消息查询与本地已读状态更新。
func testOpenAPIChatHistoryAndReadSuccess(t *testing.T) {
// srv、store、cleanup 分别是启用聊天应用的服务、夹具存储和资源释放函数。
srv, store, cleanup := newTestServerWithChat(t)
defer cleanup()
// saveErr 表示写入可查询聊天消息失败。
_, _, saveErr := store.Chats.SaveMessage(context.Background(), db.ChatSession{CookieID: "acc1", ChatID: "chat-contract", BuyerID: "buyer-contract", BuyerName: "契约买家"}, db.ChatMessage{MessageKey: "message-contract", Direction: "incoming", SenderID: "buyer-contract", SenderName: "契约买家", MessageType: "text", Content: "契约消息", Status: "received", SentAt: 1}, true)
if saveErr != nil {
t.Fatalf("写入聊天夹具失败: %v", saveErr)
}
// handler 是当前场景的真实 Router。
handler := srv.Router()
// sessionCookie 是当前管理员认证会话。
sessionCookie := loginHelper(t, handler)
// requests 保存消息读取与已读更新的真实版本化请求。
requests := []*http.Request{
httptest.NewRequest(http.MethodGet, "/api/v1/chat/messages?account_id=acc1&chat_id=chat-contract", nil),
httptest.NewRequest(http.MethodPost, "/api/v1/chat/read", strings.NewReader(`{"account_id":"acc1","chat_id":"chat-contract"}`)),
}
// request 是当前待验证的聊天 HTTP 请求。
for _, request := range requests {
request.Header.Set("Content-Type", "application/json")
request.AddCookie(sessionCookie)
// recorder 保存真实 handler 的成功响应。
recorder := httptest.NewRecorder()
handler.ServeHTTP(recorder, request)
assertOpenAPIRecordedSuccessResponse(t, request, recorder)
}
// channelResult、channelErr 保存删除场景所需通知渠道的插入结果。
channelResult, channelErr := store.DB.ExecContext(context.Background(), `INSERT INTO notification_channels (name,type,config,enabled,user_id) VALUES ('contract-delete','webhook','{}',1,1)`)
if channelErr != nil {
t.Fatalf("创建删除通知渠道失败: %v", channelErr)
}
// channelID、channelIDErr 保存删除场景通知渠道主键及读取错误。
channelID, channelIDErr := channelResult.LastInsertId()
if channelIDErr != nil {
t.Fatalf("读取删除通知渠道主键失败: %v", channelIDErr)
}
// notificationResult、notificationErr 保存待删除消息通知夹具的主键及插入结果。
notificationResult, notificationErr := store.DB.ExecContext(context.Background(), `INSERT INTO message_notifications (cookie_id,channel_id,enabled) VALUES ('acc1',?,1)`, channelID)
if notificationErr != nil {
t.Fatalf("创建消息通知夹具失败: %v", notificationErr)
}
// notificationID、notificationIDErr 保存消息通知主键及读取错误。
notificationID, notificationIDErr := notificationResult.LastInsertId()
if notificationIDErr != nil {
t.Fatalf("读取消息通知主键失败: %v", notificationIDErr)
}
// deleteRequest 是删除单条消息通知的版本化请求。
deleteRequest := httptest.NewRequest(http.MethodDelete, "/api/v1/notifications/messages/"+strconv.FormatInt(notificationID, 10), nil)
deleteRequest.AddCookie(sessionCookie)
// deleteRecorder 保存删除响应。
deleteRecorder := httptest.NewRecorder()
handler.ServeHTTP(deleteRecorder, deleteRequest)
assertOpenAPIRecordedSuccessResponse(t, deleteRequest, deleteRecorder)
}
// testOpenAPILocalItemAndManualShipSuccess 覆盖无需平台请求的商品创建和状态型手动发货成功响应。
func testOpenAPILocalItemAndManualShipSuccess(t *testing.T) {
// srv、store、cleanup 分别是服务、订单夹具存储和资源释放函数。
srv, store, cleanup := newTestServer(t)
defer cleanup()
// seedErr 表示写入待发货订单夹具失败。
_, seedErr := store.DB.ExecContext(context.Background(), `INSERT INTO orders (order_id,item_id,buyer_id,order_status,cookie_id,chat_id) VALUES ('contract-manual-ship','contract-item','buyer-contract','2','acc1','chat-contract')`)
if seedErr != nil {
t.Fatalf("写入手动发货订单失败: %v", seedErr)
}
// handler 是当前场景的真实 Router。
handler := srv.Router()
// sessionCookie 是当前管理员认证会话。
sessionCookie := loginHelper(t, handler)
// requests 保存商品创建和状态型手动发货的版本化请求。
requests := []*http.Request{
httptest.NewRequest(http.MethodPost, "/api/v1/items/acc1", strings.NewReader(`{"item_id":"contract-created","item_title":"契约商品","item_price":"10.00"}`)),
httptest.NewRequest(http.MethodPost, "/api/v1/orders/manual-ship", strings.NewReader(`{"order_ids":["contract-manual-ship"],"ship_mode":"status_only"}`)),
}
// request 是当前待验证的本地资源请求。
for _, request := range requests {
request.Header.Set("Content-Type", "application/json")
request.AddCookie(sessionCookie)
// recorder 保存当前请求的完整成功响应。
recorder := httptest.NewRecorder()
handler.ServeHTTP(recorder, request)
assertOpenAPIRecordedSuccessResponse(t, request, recorder)
}
}
// testOpenAPIItemCategoryRecommendationSuccess 覆盖商品类目推荐的本地 MTOP 成功响应。
func testOpenAPIItemCategoryRecommendationSuccess(t *testing.T) {
// srv、_、cleanup 分别是服务、无需直接读取的存储和资源释放函数。
srv, _, cleanup := newTestServer(t)
defer cleanup()
// client 是仅返回类目推荐结构的本地 MTOP 客户端。
client := mtop.NewClient()
client.HTTPClient = &http.Client{Transport: roundTripFunc(func(request *http.Request) (*http.Response, error) {
// request 是类目推荐的 MTOP 请求;本场景只需返回确定性成功数据。
return &http.Response{StatusCode: http.StatusOK, Header: make(http.Header), Body: io.NopCloser(strings.NewReader(`{"ret":["SUCCESS::调用成功"],"data":{"cardList":[{"cardData":{"propertyId":"-10000","propertyName":"分类","valuesList":[{"catId":"5001","catName":"虚拟商品","channelCatId":"6001","isClicked":"1"}]}}]}}`)), Request: request}, nil
})}
setTestMTop(srv, client)
// handler 是当前场景的真实 Router。
handler := srv.Router()
// sessionCookie 是当前管理员认证会话。
sessionCookie := loginHelper(t, handler)
// request 是商品类目推荐的版本化请求。
request := httptest.NewRequest(http.MethodPost, "/api/v1/items/publish-categories/recommend", strings.NewReader(`{"cookie_id":"acc1","keyword":"资料"}`))
request.Header.Set("Content-Type", "application/json")
request.AddCookie(sessionCookie)
// recorder 保存真实 handler 的成功响应。
recorder := httptest.NewRecorder()
handler.ServeHTTP(recorder, request)
assertOpenAPIRecordedSuccessResponse(t, request, recorder)
}
// testOpenAPIPublishBatchPreviewSuccess 覆盖批量发布预检的真实 multipart 成功响应。
func testOpenAPIPublishBatchPreviewSuccess(t *testing.T) {
// srv、_、cleanup 分别是服务、无需直接读取的存储和资源释放函数。
srv, _, cleanup := newTestServer(t)
defer cleanup()
// handler 是当前场景的真实 Router。
handler := srv.Router()
// sessionCookie 是当前管理员认证会话。
sessionCookie := loginHelper(t, handler)
// body 保存预检上传的 multipart 编码结果。
var body bytes.Buffer
// writer 负责组装真实预检入口需要的默认账号、CSV 和图片压缩包字段。
writer := multipart.NewWriter(&body)
_ = writer.WriteField("default_cookie_id", "acc1")
_ = writer.WriteField("fallback_category_id", "5001")
_ = writer.WriteField("fallback_category_name", "虚拟商品")
_ = writer.WriteField("fallback_channel_category_id", "6001")
// csvFile、csvErr 分别是预检 CSV 文件写入器和创建错误。
csvFile, csvErr := writer.CreateFormFile("file", "products.csv")
if csvErr != nil {
t.Fatalf("创建预检 CSV 失败: %v", csvErr)
}
// writeErr 表示写入测试预检 CSV 内容失败。
if _, writeErr := io.WriteString(csvFile, "账号ID,标题,价格,库存,图片\nacc1,契约商品,12.50,1,\n"); writeErr != nil {
t.Fatalf("写入预检 CSV 失败: %v", writeErr)
}
// closeErr 表示完成预检 multipart 编码失败。
if closeErr := writer.Close(); closeErr != nil {
t.Fatalf("关闭预检 multipart 失败: %v", closeErr)
}
// request 是批量发布预检的版本化上传请求。
request := httptest.NewRequest(http.MethodPost, "/api/v1/items/publish-batches/preview", &body)
request.Header.Set("Content-Type", writer.FormDataContentType())
request.AddCookie(sessionCookie)
// recorder 保存真实预检成功响应。
recorder := httptest.NewRecorder()
handler.ServeHTTP(recorder, request)
assertOpenAPIRecordedSuccessResponse(t, request, recorder)
}
// testOpenAPIUncertainNotificationSuccess 覆盖用户和管理员不确定通知摘要的真实成功响应。
func testOpenAPIUncertainNotificationSuccess(t *testing.T) {
// srv、store、cleanup 分别是服务、通知夹具存储和资源释放函数。
srv, store, cleanup := newTestServer(t)
defer cleanup()
// result、insertErr 分别是渠道插入结果和数据库错误。
result, insertErr := store.DB.ExecContext(context.Background(), `INSERT INTO notification_channels (name,type,config,enabled,user_id) VALUES ('contract','webhook','{}',1,1)`)
if insertErr != nil {
t.Fatalf("创建通知渠道失败: %v", insertErr)
}
// channelID、idErr 分别是渠道标识和读取主键错误。
channelID, idErr := result.LastInsertId()
if idErr != nil {
t.Fatalf("读取通知渠道标识失败: %v", idErr)
}
// enqueueErr 表示写入 outbox 夹具失败。
enqueueErr := store.Notifications.EnqueueOutbox(context.Background(), []db.NotificationOutboxInput{{ChannelID: channelID, EventType: "contract"}})
if enqueueErr != nil {
t.Fatalf("写入通知 outbox 失败: %v", enqueueErr)
}
// claimed、claimErr 分别是被本地 worker 领取的 outbox 项和领取错误。
claimed, claimErr := store.Notifications.ClaimOutbox(context.Background(), "contract-worker", time.Now(), 1)
if claimErr != nil || len(claimed) != 1 {
t.Fatalf("领取通知 outbox 失败: items=%+v err=%v", claimed, claimErr)
}
// marked、markErr 分别表示不确定状态是否写入及写入错误。
if marked, markErr := store.Notifications.MarkOutboxUncertain(context.Background(), claimed[0].ID, "contract-worker", "contract-error"); markErr != nil || !marked {
t.Fatalf("标记不确定通知失败: marked=%v err=%v", marked, markErr)
}
// handler 是当前场景的真实 Router。
handler := srv.Router()
// sessionCookie 是管理员认证会话。
sessionCookie := loginHelper(t, handler)
// requests 保存用户与管理员不确定通知列表请求。
requests := []*http.Request{
httptest.NewRequest(http.MethodGet, "/api/v1/notifications/outbox/uncertain?limit=10", nil),
httptest.NewRequest(http.MethodGet, "/api/v1/admin/notifications/outbox/uncertain?limit=10", nil),
}
// request 是当前待验证的不确定通知查询请求。
for _, request := range requests {
request.AddCookie(sessionCookie)
// recorder 保存当前真实成功响应。
recorder := httptest.NewRecorder()
handler.ServeHTTP(recorder, request)
assertOpenAPIRecordedSuccessResponse(t, request, recorder)
}
}
// _ 使用 encoding/json 保持本文件与未来需解码的覆盖场景共用稳定依赖。
var _ = json.Valid
// testOpenAPIChatSendSuccess 使用最小聊天端口验证文字和图片成功响应的 HTTP 形状。
func testOpenAPIChatSendSuccess(t *testing.T) {
// srv、_、cleanup 分别是服务、无需直接读取的存储和资源释放函数。
srv, _, cleanup := newTestServer(t)
defer cleanup()
// srv.applications.chat 注入只返回确定性消息的测试端口,避免调用真实账号运行时。
srv.applications.chat = contractChatPort{}
// handler 是当前场景的真实 Router。
handler := srv.Router()
// sessionCookie 是管理员认证会话。
sessionCookie := loginHelper(t, handler)
// textRequest 是文字消息发送请求。
textRequest := httptest.NewRequest(http.MethodPost, "/api/v1/chat/messages", strings.NewReader(`{"account_id":"acc1","chat_id":"chat","buyer_id":"buyer","text":"hello"}`))
textRequest.Header.Set("Content-Type", "application/json")
textRequest.AddCookie(sessionCookie)
// textRecorder 保存文字发送响应。
textRecorder := httptest.NewRecorder()
handler.ServeHTTP(textRecorder, textRequest)
assertOpenAPIRecordedSuccessResponse(t, textRequest, textRecorder)
// imageBody 保存图片发送请求的 multipart 内容。
var imageBody bytes.Buffer
// imageWriter 负责写入图片发送字段。
imageWriter := multipart.NewWriter(&imageBody)
_ = imageWriter.WriteField("account_id", "acc1")
_ = imageWriter.WriteField("chat_id", "chat")
_ = imageWriter.WriteField("buyer_id", "buyer")
// imageFile 是聊天图片表单文件。
imageFile, imageErr := imageWriter.CreatePart(textproto.MIMEHeader{"Content-Disposition": []string{`form-data; name="image"; filename="chat.png"`}, "Content-Type": []string{"image/png"}})
if imageErr != nil {
t.Fatalf("创建聊天图片失败: %v", imageErr)
}
_, _ = imageFile.Write([]byte{0x89, 0x50, 0x4e, 0x47})
_ = imageWriter.Close()
// imageRequest 是图片发送版本化请求。
imageRequest := httptest.NewRequest(http.MethodPost, "/api/v1/chat/images", &imageBody)
imageRequest.Header.Set("Content-Type", imageWriter.FormDataContentType())
imageRequest.AddCookie(sessionCookie)
// imageRecorder 保存图片发送响应。
imageRecorder := httptest.NewRecorder()
handler.ServeHTTP(imageRecorder, imageRequest)
assertOpenAPIRecordedSuccessResponse(t, imageRequest, imageRecorder)
}
// testOpenAPIItemSyncSuccess 使用本地 MTOP 返回商品列表,验证全量和分页同步响应。
func testOpenAPIItemSyncSuccess(t *testing.T) {
// srv、_、cleanup 分别是服务、无需直接读取的存储和资源释放函数。
srv, _, cleanup := newTestServer(t)
defer cleanup()
// client 是返回最小有效商品卡片的本地 MTOP 客户端。
client := mtop.NewClient()
client.HTTPClient = &http.Client{Transport: roundTripFunc(func(request *http.Request) (*http.Response, error) {
// request 是同步请求;返回值只包含本地同步需要的非敏感商品字段。
return &http.Response{StatusCode: http.StatusOK, Header: make(http.Header), Body: io.NopCloser(strings.NewReader(`{"ret":["SUCCESS::调用成功"],"data":{"cardList":[{"cardData":{"id":"sync-contract","title":"同步商品","priceInfo":{"price":"10.00","preText":"¥"},"picInfo":{"picUrl":"https://img.example/s.png"},"detailParams":{"itemId":"sync-contract"}}}]}}`)), Request: request}, nil
})}
setTestMTop(srv, client)
// handler 是当前场景的真实 Router。
handler := srv.Router()
// sessionCookie 是管理员认证会话。
sessionCookie := loginHelper(t, handler)
// requests 保存全量和分页同步请求。
requests := []*http.Request{
httptest.NewRequest(http.MethodPost, "/api/v1/items/get-all-from-account", strings.NewReader(`{"cookie_id":"acc1","page_size":10}`)),
httptest.NewRequest(http.MethodPost, "/api/v1/items/get-by-page", strings.NewReader(`{"cookie_id":"acc1","page_number":1,"page_size":10}`)),
}
// request 是当前同步请求。
for _, request := range requests {
request.Header.Set("Content-Type", "application/json")
request.AddCookie(sessionCookie)
// recorder 保存真实同步响应。
recorder := httptest.NewRecorder()
handler.ServeHTTP(recorder, request)
assertOpenAPIRecordedSuccessResponse(t, request, recorder)
}
}
// testOpenAPIItemPublishSuccess 注入商品发布端口并验证 multipart 发布成功响应。
func testOpenAPIItemPublishSuccess(t *testing.T) {
// srv、_、cleanup 分别是服务、无需直接读取的存储和资源释放函数。
srv, _, cleanup := newTestServer(t)
defer cleanup()
srv.applications.itemSinglePublish = contractItemPublishPort{}
// handler 是当前场景的真实 Router。
handler := srv.Router()
// sessionCookie 是管理员认证会话。
sessionCookie := loginHelper(t, handler)
// body 保存发布接口要求的 multipart 字段。
var body bytes.Buffer
// writer 负责组装发布表单。
writer := multipart.NewWriter(&body)
_ = writer.WriteField("cookie_id", "acc1")
_ = writer.WriteField("title", "契约发布")
_ = writer.WriteField("price", "10.00")
_ = writer.WriteField("original_price", "10.00")
_ = writer.WriteField("quantity", "1")
// image 是发布图片表单写入器。
image, imageErr := writer.CreatePart(textproto.MIMEHeader{"Content-Disposition": []string{`form-data; name="images"; filename="contract.png"`}, "Content-Type": []string{"image/png"}})
if imageErr != nil {
t.Fatalf("创建发布图片失败: %v", imageErr)
}
_, _ = image.Write([]byte{0x89, 0x50, 0x4e, 0x47})
_ = writer.Close()
// request 是真实版本化商品发布请求。
request := httptest.NewRequest(http.MethodPost, "/api/v1/items/publish", &body)
request.Header.Set("Content-Type", writer.FormDataContentType())
request.AddCookie(sessionCookie)
// recorder 保存真实发布响应。
recorder := httptest.NewRecorder()
handler.ServeHTTP(recorder, request)
assertOpenAPIRecordedSuccessResponse(t, request, recorder)
}
// testOpenAPIBatchLifecycleSuccess 通过预检批次覆盖批次查询、取消和删除成功响应。
func testOpenAPIBatchLifecycleSuccess(t *testing.T) {
// srv、store、cleanup 分别是服务、批次状态夹具存储和资源释放函数。
srv, store, cleanup := newTestServer(t)
defer cleanup()
// handler 是当前场景的真实 Router。
handler := srv.Router()
// sessionCookie 是管理员认证会话。
sessionCookie := loginHelper(t, handler)
// batchID 是真实预检批次标识。
batchID := previewPublishBatch(t, handler, sessionCookie)
// requests 保存批次详情、取消和删除请求;取消后批次可安全删除。
requests := []*http.Request{
httptest.NewRequest(http.MethodGet, "/api/v1/items/publish-batches/"+batchID, nil),
httptest.NewRequest(http.MethodPost, "/api/v1/items/publish-batches/"+batchID+"/cancel", nil),
httptest.NewRequest(http.MethodDelete, "/api/v1/items/publish-batches/"+batchID, nil),
}
// request 是当前批次生命周期请求。
for _, request := range requests {
request.AddCookie(sessionCookie)
// recorder 保存当前批次成功响应。
recorder := httptest.NewRecorder()
handler.ServeHTTP(recorder, request)
assertOpenAPIRecordedSuccessResponse(t, request, recorder)
}
// startBatchID 是另一条真实预检批次标识,专门覆盖启动 operation。
startBatchID := previewPublishBatch(t, handler, sessionCookie)
// startRequest 是启动批量发布的版本化请求。
startRequest := httptest.NewRequest(http.MethodPost, "/api/v1/items/publish-batches", strings.NewReader(`{"preview_id":"`+startBatchID+`"}`))
startRequest.Header.Set("Content-Type", "application/json")
startRequest.AddCookie(sessionCookie)
// startRecorder 保存启动响应。
startRecorder := httptest.NewRecorder()
handler.ServeHTTP(startRecorder, startRequest)
assertOpenAPIRecordedSuccessResponse(t, startRequest, startRecorder)
// retryBatchID 是预置为失败状态的批次标识,确保重试 operation 真实进入成功分支。
retryBatchID := previewPublishBatch(t, handler, sessionCookie)
// updateErr 表示写入批次失败终态失败。
if _, updateErr := store.DB.ExecContext(context.Background(), `UPDATE item_publish_batches SET status='failed',failed_count=1 WHERE id=?`, retryBatchID); updateErr != nil {
t.Fatalf("设置重试批次状态失败: %v", updateErr)
}
// updateErr 表示写入失败批次明细失败。
if _, updateErr := store.DB.ExecContext(context.Background(), `UPDATE item_publish_batch_rows SET status='failed',error_message='contract failure' WHERE batch_id=?`, retryBatchID); updateErr != nil {
t.Fatalf("设置重试批次明细失败: %v", updateErr)
}
// retryRequest 是重试失败明细的版本化请求。
retryRequest := httptest.NewRequest(http.MethodPost, "/api/v1/items/publish-batches/"+retryBatchID+"/retry-failed", nil)
retryRequest.AddCookie(sessionCookie)
// retryRecorder 保存重试响应。
retryRecorder := httptest.NewRecorder()
handler.ServeHTTP(retryRecorder, retryRequest)
assertOpenAPIRecordedSuccessResponse(t, retryRequest, retryRecorder)
}
// testOpenAPIAutomationResolveSuccess 写入真实死信延期任务并验证人工处理成功响应。
func testOpenAPIAutomationResolveSuccess(t *testing.T) {
// srv、store、cleanup 分别是服务、自动化夹具存储和资源释放函数。
srv, store, cleanup := newTestServer(t)
defer cleanup()
// ruleResult、ruleErr 保存异常运行归属规则的插入结果。
ruleResult, ruleErr := store.DB.ExecContext(context.Background(), `INSERT INTO automation_rules (user_id,cookie_id,name,trigger_type,enabled,config_json) VALUES (1,'acc1','contract-rule','order_paid',1,'{}')`)
if ruleErr != nil {
t.Fatalf("写入自动化规则失败: %v", ruleErr)
}
// ruleID、ruleIDErr 保存异常运行归属规则主键及读取错误。
ruleID, ruleIDErr := ruleResult.LastInsertId()
if ruleIDErr != nil {
t.Fatalf("读取自动化规则主键失败: %v", ruleIDErr)
}
// runResult、runErr 保存待处理异常运行的插入结果。
runResult, runErr := store.DB.ExecContext(context.Background(), `INSERT INTO automation_runs (rule_id,cookie_id,trigger_type,trigger_key,status,raw_event_json,error_message) VALUES (?,?,?,'contract-run','needs_review','{"AccountID":"acc1"}','contract failure')`, ruleID, "acc1", "order_paid")
if runErr != nil {
t.Fatalf("写入自动化异常运行失败: %v", runErr)
}
// runID、runIDErr 保存待处理异常运行主键及读取错误。
runID, runIDErr := runResult.LastInsertId()
if runIDErr != nil {
t.Fatalf("读取自动化异常运行主键失败: %v", runIDErr)
}
// handler 是当前场景的真实 Router。
handler := srv.Router()
// sessionCookie 是管理员认证会话。
sessionCookie := loginHelper(t, handler)
// runRequest 是取消异常运行的版本化请求。
runRequest := httptest.NewRequest(http.MethodPost, "/api/v1/automation-runs/"+strconv.FormatInt(runID, 10)+"/resolve", strings.NewReader(`{"resolution":"cancel"}`))
runRequest.Header.Set("Content-Type", "application/json")
runRequest.AddCookie(sessionCookie)
// runRecorder 保存异常运行处理响应。
runRecorder := httptest.NewRecorder()
handler.ServeHTTP(runRecorder, runRequest)
assertOpenAPIRecordedSuccessResponse(t, runRequest, runRecorder)
// insertErr 表示写入死信延期任务失败。
_, insertErr := store.DB.ExecContext(context.Background(), `INSERT INTO automation_pending_tasks (task_key,cookie_id,trigger_type,task_json,status,attempt_count,error_message) VALUES ('contract-task','acc1','contract','{}','dead_letter',3,'failed')`)
if insertErr != nil {
t.Fatalf("写入自动化死信任务失败: %v", insertErr)
}
// taskID 保存刚刚写入的延期任务主键。
var taskID int64
// scanErr 表示读取延期任务主键失败。
if scanErr := store.DB.QueryRowContext(context.Background(), `SELECT id FROM automation_pending_tasks WHERE task_key='contract-task'`).Scan(&taskID); scanErr != nil {
t.Fatalf("读取自动化任务标识失败: %v", scanErr)
}
// request 是驳回延期任务的版本化请求。
request := httptest.NewRequest(http.MethodPost, "/api/v1/automation-pending-tasks/"+strconv.FormatInt(taskID, 10)+"/resolve", strings.NewReader(`{"resolution":"dismiss"}`))
request.Header.Set("Content-Type", "application/json")
request.AddCookie(sessionCookie)
// recorder 保存真实人工处理响应。
recorder := httptest.NewRecorder()
handler.ServeHTTP(recorder, request)
assertOpenAPIRecordedSuccessResponse(t, request, recorder)
}
// testOpenAPINotificationChannelTestSuccess 验证通知渠道测试的真实网络成功响应。
func testOpenAPINotificationChannelTestSuccess(t *testing.T) {
// endpoint 是接收通知测试请求的本地 Webhook。
endpoint := httptest.NewServer(http.HandlerFunc(func(responseWriter http.ResponseWriter, request *http.Request) {
responseWriter.WriteHeader(http.StatusNoContent)
}))
defer endpoint.Close()
// srv、_、cleanup 分别是服务、无需直接读取的存储和资源释放函数。
srv, _, cleanup := newTestServer(t)
defer cleanup()
// srv.applications.notificationChannels 注入成功替身,避免测试依赖进程级通知器。
srv.applications.notificationChannels = contractNotificationChannelsPort{}
// handler 是当前场景的真实 Router。
handler := srv.Router()
// sessionCookie 是管理员认证会话。
sessionCookie := loginHelper(t, handler)
// createRequest 创建本地 Webhook 渠道。
createRequest := httptest.NewRequest(http.MethodPost, "/api/v1/notifications/channels", strings.NewReader(`{"name":"契约Webhook","type":"webhook","config":"{\"url\":\"`+endpoint.URL+`\"}","enabled":true}`))
createRequest.Header.Set("Content-Type", "application/json")
createRequest.AddCookie(sessionCookie)
// createRecorder 保存渠道创建响应。
createRecorder := httptest.NewRecorder()
handler.ServeHTTP(createRecorder, createRequest)
assertOpenAPIRecordedSuccessResponse(t, createRequest, createRecorder)
// channelID 保存创建响应中的渠道主键。
var created struct {
ID int64 `json:"id"`
}
// decodeErr 表示解析通知渠道创建响应失败。
if decodeErr := json.Unmarshal(createRecorder.Body.Bytes(), &created); decodeErr != nil || created.ID <= 0 {
t.Fatalf("渠道创建响应无效: %s", createRecorder.Body.String())
}
// testRequest 是调用渠道测试的版本化请求。
testRequest := httptest.NewRequest(http.MethodPost, "/api/v1/notifications/channels/"+strconv.FormatInt(created.ID, 10)+"/test", nil)
testRequest.AddCookie(sessionCookie)
// testRecorder 保存渠道测试成功响应。
testRecorder := httptest.NewRecorder()
handler.ServeHTTP(testRecorder, testRequest)
assertOpenAPIRecordedSuccessResponse(t, testRequest, testRecorder)
}
// testOpenAPIAccountTaskRunSuccess 注入账号任务端口并验证手动运行响应。
func testOpenAPIAccountTaskRunSuccess(t *testing.T) {
// srv、_、cleanup 分别是服务、无需直接读取的存储和资源释放函数。
srv, _, cleanup := newTestServer(t)
defer cleanup()
srv.applications.accountTasks = contractAccountTasksPort{}
// handler 是当前场景的真实 Router。
handler := srv.Router()
// sessionCookie 是管理员认证会话。
sessionCookie := loginHelper(t, handler)
// request 是手动自动评价运行请求。
request := httptest.NewRequest(http.MethodPost, "/api/v1/account-tasks/acc1/run", strings.NewReader(`{"task_type":"auto_rate"}`))
request.Header.Set("Content-Type", "application/json")
request.AddCookie(sessionCookie)
// recorder 保存任务运行响应。
recorder := httptest.NewRecorder()
handler.ServeHTTP(recorder, request)
assertOpenAPIRecordedSuccessResponse(t, request, recorder)
}
// contractChatPort 是只返回确定性消息的聊天 HTTP 应用端口。
type contractChatPort struct{}
// SendingAvailable 报告测试端口支持文字发送。
func (contractChatPort) SendingAvailable() bool { return true }
// ImageUploadAvailable 报告测试端口支持图片上传。
func (contractChatPort) ImageUploadAvailable() bool { return true }
// Subscribe 返回空事件流,当前场景不验证 WebSocket。
func (contractChatPort) Subscribe(context.Context, int64) (<-chan chatapp.Event, func(), error) {
return nil, func() {}, nil
}
// RefreshConversations 返回空联系人页。
func (contractChatPort) RefreshConversations(context.Context, string, int64, int) (chatapp.ConversationPage, error) {
return chatapp.ConversationPage{}, nil
}
// RefreshHistory 返回不可用错误,使查询回退本地存储。
func (contractChatPort) RefreshHistory(context.Context, string, string, int64, int, chatapp.Session) (chatapp.HistoryPage, error) {
return chatapp.HistoryPage{}, chatapp.ErrRefreshUnavailable
}
// SendText 返回确定性外发消息。
func (contractChatPort) SendText(context.Context, chatapp.OutgoingInput) (*chatapp.Message, error) {
return &chatapp.Message{AccountID: "acc1", ChatID: "chat", MessageKey: "contract-message", Direction: "outgoing", MessageType: "text", Content: "hello", Status: "sent"}, nil
}
// SendImage 返回确定性外发图片消息。
func (contractChatPort) SendImage(context.Context, chatapp.ImageInput) (*chatapp.Message, error) {
return &chatapp.Message{AccountID: "acc1", ChatID: "chat", MessageKey: "contract-image", Direction: "outgoing", MessageType: "image", Content: "https://img.example/i.png", Status: "sent"}, nil
}
// ListStoredMessages 返回空消息页。
func (contractChatPort) ListStoredMessages(context.Context, int64, string, string, int64, int) (chatapp.Page, error) {
return chatapp.Page{}, nil
}
// ListSessions 返回空会话集合。
func (contractChatPort) ListSessions(context.Context, int64, string, int) ([]chatapp.Session, error) {
return nil, nil
}
// FindSession 返回空会话。
func (contractChatPort) FindSession(context.Context, int64, string, string) (chatapp.Session, error) {
return chatapp.Session{}, nil
}
// ResolveReadMessageID 返回有效测试平台消息标识。
func (contractChatPort) ResolveReadMessageID(context.Context, string, string, string) string {
return "contract.PNM"
}
// CleanupEmptySessions 在测试端口中无副作用。
func (contractChatPort) CleanupEmptySessions(context.Context, string) error { return nil }
// OwnsAccount 始终确认测试账号归属。
func (contractChatPort) OwnsAccount(context.Context, int64, string) (bool, error) { return true, nil }
// MarkRead 确认本地已读更新成功。
func (contractChatPort) MarkRead(context.Context, int64, string, string) error { return nil }
// ReportPlatformRead 确认平台已读上报成功。
func (contractChatPort) ReportPlatformRead(context.Context, string, string, []map[string]any) error {
return nil
}
// ResolveSessionIdentity 保持测试会话为空。
func (contractChatPort) ResolveSessionIdentity(context.Context, chatapp.Session) (chatapp.Session, error) {
return chatapp.Session{}, nil
}
// RefreshSessionIdentities 返回空会话集合。
func (contractChatPort) RefreshSessionIdentities(context.Context, string, []chatapp.Session) ([]chatapp.Session, error) {
return nil, nil
}
// contractItemPublishPort 是只返回确定性商品结果的单商品发布端口。
type contractItemPublishPort struct{}
// PublishSingle 返回确定性远端发布结果。
func (contractItemPublishPort) PublishSingle(context.Context, itemapp.PublishInput) (itemapp.PublishOutcome, error) {
return itemapp.PublishOutcome{Result: &itemapp.PublishResult{ItemID: "contract-published", ItemURL: "https://item.example/contract", Title: "契约发布", PriceText: "10.00", Quantity: 1}}, nil
}
// contractAccountTasksPort 是只返回确定性统计结果的账号任务端口。
type contractAccountTasksPort struct{}
// contractNotificationChannelsPort 是只覆盖渠道测试动作的通知渠道端口。
type contractNotificationChannelsPort struct{ NotificationChannelsPort }
// CreateChannel 返回固定渠道标识,使后续测试请求仍通过真实 HTTP handler。
func (contractNotificationChannelsPort) CreateChannel(context.Context, int64, notificationsapp.ChannelInput) (int64, error) {
return 1, nil
}
// TestChannel 将渠道测试视为已由本地替身成功发送。
func (contractNotificationChannelsPort) TestChannel(context.Context, int64, int64, time.Time) error {
return nil
}
// GetSettings 返回测试账号默认任务设置。
func (contractAccountTasksPort) GetSettings(context.Context, string) (automationapp.AccountTaskSettings, error) {
return automationapp.AccountTaskSettings{CookieID: "acc1"}, nil
}
// UpdateSettings 返回规范化后的测试设置。
func (contractAccountTasksPort) UpdateSettings(context.Context, automationapp.AccountTaskSettings) (automationapp.AccountTaskSettings, error) {
return automationapp.AccountTaskSettings{CookieID: "acc1"}, nil
}
// ListRuns 返回空运行记录。
func (contractAccountTasksPort) ListRuns(context.Context, string, int) ([]automationapp.AccountTaskRun, error) {
return nil, nil
}
// Run 返回包含一个成功动作的任务摘要。
func (contractAccountTasksPort) Run(context.Context, string, string) (automationapp.TaskSummary, error) {
return automationapp.TaskSummary{TaskType: automationapp.TaskAutoRate, Success: 1}, nil
}
@@ -3,10 +3,13 @@ package server
import (
"bytes"
"context"
"encoding/json"
"io"
"net/http"
"net/http/httptest"
"path/filepath"
"sort"
"strconv"
"strings"
"testing"
@@ -15,6 +18,74 @@ import (
"github.com/getkin/kin-openapi/routers/legacy"
)
// TestOpenAPISuccessContractCoverage 从唯一 OpenAPI 文档自动枚举普通 operation,确认每个 operation 都有真实成功响应断言记录。
func TestOpenAPISuccessContractCoverage(t *testing.T) {
// scenarios 是按领域组织的真实 Router 成功场景;覆盖集合由每次成功断言的 operationId 自动产生。
scenarios := []struct {
// name 是失败输出使用的稳定领域名称。
name string
// run 会执行该领域完整的真实 HTTP 成功场景。
run func(*testing.T)
}{
{name: "session-and-qr", run: TestOpenAPISessionAndQRResponses},
{name: "accounts-and-system", run: TestOpenAPIAccountAndSystemResponses},
{name: "query-chat-orders", run: TestOpenAPIQueryChatAndOrderResponses},
{name: "items-and-cards", run: TestOpenAPIItemAndCardResponses},
{name: "notifications", run: TestOpenAPINotificationResponses},
{name: "versioned-session", run: TestVersionedSessionRoutesPreserveLegacyContracts},
{name: "versioned-account", run: TestVersionedAccountRoutesPreserveLegacyContracts},
{name: "versioned-account-credentials", run: TestVersionedAccountCredentialRoutesPreserveLegacyContracts},
{name: "versioned-account-settings", run: TestVersionedAccountSettingsRoutesPreserveLegacyContracts},
{name: "versioned-items", run: TestVersionedItemRoutesPreserveLegacyContracts},
{name: "versioned-orders", run: TestVersionedOrderRoutesPreserveLegacyContracts},
{name: "versioned-order-refresh", run: TestVersionedOrderRefreshAndBatchRoutesPreserveLegacyContracts},
{name: "versioned-qr", run: TestVersionedQRLoginRoutesPreserveLegacyContracts},
{name: "versioned-admin-analytics", run: TestVersionedAdminAnalyticsRoutesPreserveLegacyContracts},
{name: "versioned-settings-cards-notifications", run: TestVersionedSettingsCardNotificationRoutesPreserveLegacyContracts},
{name: "versioned-item-batches", run: TestVersionedItemBatchRoutesPreserveLegacyContracts},
{name: "versioned-chat-tasks", run: TestVersionedChatTaskRoutesPreserveLegacyContracts},
{name: "versioned-replies", run: TestVersionedReplyRoutesPreserveLegacyContracts},
{name: "versioned-remaining", run: TestVersionedRemainingRoutesPreserveLegacyContracts},
{name: "named-success", run: TestNamedSuccessResponseContracts},
{name: "remaining-success", run: TestRemainingSuccessResponseContracts},
{name: "settings-cards-notifications-batch", run: TestSettingsCardsNotificationsBatchContracts},
{name: "dynamic-success", run: TestDynamicCompatibilitySuccessContracts},
{name: "reply-and-account-task-success", run: TestReplyAndAccountTaskSuccessResponseContracts},
{name: "analytics-admin-public-success", run: TestAnalyticsAdminAndPublicSuccessResponseContracts},
{name: "local-resource-mutations", run: TestOpenAPILocalResourceMutationResponses},
{name: "remaining-versioned-success", run: TestOpenAPIRemainingVersionedSuccessResponses},
}
// scenario 是当前执行的领域真实响应场景。
for _, scenario := range scenarios {
// scenario 保存当前领域成功场景,子测试名称和执行函数必须保持同一实例。
scenario := scenario
t.Run(scenario.name, func(t *testing.T) {
scenario.run(t)
})
}
// document 是包含全部 operation 的唯一 OpenAPI 契约。
document := loadOpenAPIContractForCoverage(t)
// missing 保存未被成功断言记录、且没有显式特殊校验的 operationId。
missing := make([]string, 0)
for _, path := range document.Paths.Keys() { // path 是当前 OpenAPI 路径模板。
// pathItem 保存该模板下声明的全部 HTTP operation。
pathItem := document.Paths.Find(path)
for _, operation := range pathItem.Operations() { // operation 是当前待检查的 OpenAPI operation。
if openAPIContractSuccessExceptionKind(operation) != "" {
continue
}
// exists 表示该 operation 是否已由真实成功响应记录。
if _, exists := openAPISuccessOperations.Load(operation.OperationID); !exists {
missing = append(missing, operation.OperationID)
}
}
}
sort.Strings(missing)
if len(missing) > 0 {
t.Fatalf("缺少真实成功响应契约场景: %s", strings.Join(missing, ", "))
}
}
// assertOpenAPIResponse 验证真实 HTTP 响应的状态码、Content-Type 和 JSON 形状符合对应 OpenAPI operation。
func assertOpenAPIResponse(t *testing.T, request *http.Request, recorder *httptest.ResponseRecorder) {
t.Helper()
@@ -57,6 +128,9 @@ func assertOpenAPISuccessResponse(t *testing.T, request *http.Request, recorder
t.Fatalf("成功响应状态错误: %s %s status=%d body=%s", request.Method, request.URL.Path, recorder.Code, recorder.Body.String())
}
assertOpenAPIResponse(t, request, recorder)
// operationID 是从请求匹配的 OpenAPI operation 读取的稳定成功覆盖键。
operationID := openAPIOperationIDForRequest(t, request)
openAPISuccessOperations.Store(operationID, struct{}{})
}
// assertOpenAPIExpectedStatusResponse 验证非 200 成功状态的真实响应仍符合 operation 契约。
@@ -66,6 +140,127 @@ func assertOpenAPIExpectedStatusResponse(t *testing.T, request *http.Request, re
t.Fatalf("成功响应状态错误: %s %s status=%d want=%d body=%s", request.Method, request.URL.Path, recorder.Code, wantStatus, recorder.Body.String())
}
assertOpenAPIResponse(t, request, recorder)
// operationID 是从请求匹配的 OpenAPI operation 读取的稳定成功覆盖键。
operationID := openAPIOperationIDForRequest(t, request)
openAPISuccessOperations.Store(operationID, struct{}{})
}
// assertOpenAPIRecordedSuccessResponse 验证任意 2xx 的真实响应并记录其 operationId,供已存在的兼容路由成功场景复用。
func assertOpenAPIRecordedSuccessResponse(t *testing.T, request *http.Request, recorder *httptest.ResponseRecorder) {
t.Helper()
if recorder.Code < http.StatusOK || recorder.Code >= http.StatusMultipleChoices {
t.Fatalf("成功响应状态错误: %s %s status=%d body=%s", request.Method, request.URL.Path, recorder.Code, recorder.Body.String())
}
assertOpenAPIResponse(t, request, recorder)
// operationID 是从成功请求匹配出的稳定 OpenAPI operation 标识。
operationID := openAPIOperationIDForRequest(t, request)
openAPISuccessOperations.Store(operationID, struct{}{})
}
// contractRecordingHandler 在契约覆盖场景中捕获版本化成功响应,避免手写 operation 名单或遗漏断言点。
func contractRecordingHandler(t *testing.T, next http.Handler) http.Handler {
t.Helper()
return http.HandlerFunc(func(responseWriter http.ResponseWriter, request *http.Request) {
// recorder 暂存真实 handler 的完整响应,便于校验后再复制到调用方记录器。
recorder := httptest.NewRecorder()
next.ServeHTTP(recorder, request)
// headerValue 表示真实 handler 写出的响应头值集合。
for headerName, headerValues := range recorder.Header() {
responseWriter.Header()[headerName] = append([]string(nil), headerValues...)
}
responseWriter.WriteHeader(recorder.Code)
_, _ = responseWriter.Write(recorder.Body.Bytes())
if (strings.HasPrefix(request.URL.Path, "/api/v1/") || request.URL.Path == "/health") && recorder.Code >= http.StatusOK && recorder.Code < http.StatusMultipleChoices {
assertOpenAPIRecordedSuccessResponse(t, request, recorder)
}
})
}
// serveOpenAPISuccess 以真实 Router 执行一个本地可确定的版本化成功请求,并记录 operationId 作为覆盖证据。
func serveOpenAPISuccess(t *testing.T, handler http.Handler, sessionCookie *http.Cookie, method string, path string, body string) *httptest.ResponseRecorder {
t.Helper()
// request 是本次本地资源生命周期操作使用的版本化 HTTP 请求。
request := httptest.NewRequest(method, path, strings.NewReader(body))
if body != "" {
request.Header.Set("Content-Type", "application/json")
}
if sessionCookie != nil {
request.AddCookie(sessionCookie)
}
// recorder 保存真实 handler 的完整成功响应,供 OpenAPI 校验和调用方业务断言复用。
recorder := httptest.NewRecorder()
handler.ServeHTTP(recorder, request)
assertOpenAPIRecordedSuccessResponse(t, request, recorder)
return recorder
}
// openAPIOperationIDForRequest 使用唯一 OpenAPI 文档匹配真实请求并返回稳定 operationId。
func openAPIOperationIDForRequest(t *testing.T, request *http.Request) string {
t.Helper()
// specPath 是从 Server 测试目录定位到唯一 OpenAPI 契约文件的路径。
specPath := filepath.Join("..", "..", "api", "openapi.yaml")
// document、loadErr 分别是解析后的 OpenAPI 文档及其加载失败原因。
document, loadErr := openapi3.NewLoader().LoadFromFile(specPath)
if loadErr != nil {
t.Fatalf("加载 OpenAPI 契约失败: %v", loadErr)
}
// router、routerErr 分别是请求与 operation 匹配使用的 OpenAPI 路由器及其构建错误。
router, routerErr := legacy.NewRouter(document)
if routerErr != nil {
t.Fatalf("构建 OpenAPI 路由器失败: %v", routerErr)
}
// route、_、findErr 分别是匹配结果、无需读取的路径参数和路由匹配失败原因。
route, _, findErr := router.FindRoute(request)
if findErr != nil || route.Operation == nil || route.Operation.OperationID == "" {
t.Fatalf("读取成功响应 operationId 失败: %s %s err=%v", request.Method, request.URL.Path, findErr)
}
return route.Operation.OperationID
}
// openAPIContractSuccessExceptionKind 返回 operation 显式登记的特殊成功校验类别;普通 HTTP operation 返回空字符串。
func openAPIContractSuccessExceptionKind(operation *openapi3.Operation) string {
if operation == nil || operation.Extensions == nil {
return ""
}
// exception、valid 分别是 YAML 扩展对象及其是否符合受限结构。
exception, valid := operation.Extensions["x-contract-success-exception"].(map[string]any)
if !valid {
return ""
}
// kind、valid 分别是特殊校验类别及其是否为稳定字符串。
kind, valid := exception["kind"].(string)
if !valid {
return ""
}
return kind
}
// TestOpenAPIPasswordLoginDisabledOperations 验证永久关闭的密码登录 operation 真实返回 501 统一错误,而非伪造 2xx 成功响应。
func TestOpenAPIPasswordLoginDisabledOperations(t *testing.T) {
// srv、_、cleanup 分别是独立测试 Server、无需直接读取的存储和资源释放函数。
srv, _, cleanup := newTestServer(t)
defer cleanup()
// handler 是承载版本化密码登录关闭策略的真实 chi Router。
handler := srv.Router()
// sessionCookie 是访问受保护密码登录 operation 所需的管理员认证会话。
sessionCookie := loginHelper(t, handler)
// requests 保存三个永久关闭 operation 的最小版本化请求。
requests := []*http.Request{
httptest.NewRequest(http.MethodPost, "/api/v1/password-login", strings.NewReader(`{"account_id":"acc1","account":"contract-user","password":"not-a-real-secret"}`)),
httptest.NewRequest(http.MethodGet, "/api/v1/password-login/check/contract-session", nil),
httptest.NewRequest(http.MethodDelete, "/api/v1/password-login/cancel/contract-session", nil),
}
// request 是当前待验证的永久关闭版本化 operation 请求。
for _, request := range requests {
request.AddCookie(sessionCookie)
// recorder 捕获关闭策略的实际 HTTP 状态、Content-Type 和统一错误响应体。
recorder := httptest.NewRecorder()
handler.ServeHTTP(recorder, request)
if recorder.Code != http.StatusNotImplemented {
t.Fatalf("永久关闭 operation 状态错误: %s %s status=%d body=%s", request.Method, request.URL.Path, recorder.Code, recorder.Body.String())
}
assertOpenAPIResponse(t, request, recorder)
}
}
// TestOpenAPISessionAndQRResponses 验证阶段二会话与二维码主链路的成功、未认证和风控响应均满足真实契约。
@@ -333,6 +528,53 @@ func TestOpenAPIItemAndCardResponses(t *testing.T) {
handler.ServeHTTP(cardsRecorder, cardsRequest)
assertOpenAPISuccessResponse(t, cardsRequest, cardsRecorder)
// createCardRequest 是创建 data 卡券的版本化请求,供后续资源生命周期操作复用。
createCardRequest := httptest.NewRequest(http.MethodPost, "/api/v1/cards", strings.NewReader(`{"name":"OpenAPI 数据卡","type":"data","data_content":"K1","enabled":true}`))
createCardRequest.AddCookie(sessionCookie)
// createCardRecorder 捕获创建操作的具名数值主键响应。
createCardRecorder := httptest.NewRecorder()
handler.ServeHTTP(createCardRecorder, createCardRequest)
assertOpenAPISuccessResponse(t, createCardRequest, createCardRecorder)
// createdCard 保存创建操作返回的数值主键,后续请求必须使用真实归属资源。
var createdCard struct {
// ID 是本次生命周期中由服务端分配的卡券标识。
ID int64 `json:"id"`
}
// decodeErr 表示无法从已校验响应中读取资源标识的失败原因。
if decodeErr := json.Unmarshal(createCardRecorder.Body.Bytes(), &createdCard); decodeErr != nil || createdCard.ID <= 0 {
t.Fatalf("读取创建卡券标识失败: id=%d err=%v", createdCard.ID, decodeErr)
}
// cardID 是 URL 路径使用的真实卡券标识字符串。
cardID := strconv.FormatInt(createdCard.ID, 10)
// getCardRequest 是读取刚创建资源详情的成功请求。
getCardRequest := httptest.NewRequest(http.MethodGet, "/api/v1/cards/"+cardID, nil)
getCardRequest.AddCookie(sessionCookie)
// getCardRecorder 捕获详情 DTO,验证不再错误使用通用成功 envelope。
getCardRecorder := httptest.NewRecorder()
handler.ServeHTTP(getCardRecorder, getCardRequest)
assertOpenAPISuccessResponse(t, getCardRequest, getCardRecorder)
// updateCardRequest 是更新同一 data 卡券的成功请求。
updateCardRequest := httptest.NewRequest(http.MethodPut, "/api/v1/cards/"+cardID, strings.NewReader(`{"name":"OpenAPI 数据卡更新","type":"data","data_content":"K1","enabled":true}`))
updateCardRequest.AddCookie(sessionCookie)
// updateCardRecorder 捕获更新成功响应。
updateCardRecorder := httptest.NewRecorder()
handler.ServeHTTP(updateCardRecorder, updateCardRequest)
assertOpenAPISuccessResponse(t, updateCardRequest, updateCardRecorder)
// appendCardRequest 是为 data 卡券追加库存的成功请求。
appendCardRequest := httptest.NewRequest(http.MethodPost, "/api/v1/cards/"+cardID+"/append-data", strings.NewReader(`{"content":"K2\nK3"}`))
appendCardRequest.AddCookie(sessionCookie)
// appendCardRecorder 捕获追加数量响应。
appendCardRecorder := httptest.NewRecorder()
handler.ServeHTTP(appendCardRecorder, appendCardRequest)
assertOpenAPISuccessResponse(t, appendCardRequest, appendCardRecorder)
// deleteCardRequest 是删除同一资源的成功请求,保证测试不依赖虚构路径参数。
deleteCardRequest := httptest.NewRequest(http.MethodDelete, "/api/v1/cards/"+cardID, nil)
deleteCardRequest.AddCookie(sessionCookie)
// deleteCardRecorder 捕获删除成功响应。
deleteCardRecorder := httptest.NewRecorder()
handler.ServeHTTP(deleteCardRecorder, deleteCardRequest)
assertOpenAPISuccessResponse(t, deleteCardRequest, deleteCardRecorder)
// invalidUploadRequest 是缺失文件的卡券上传请求,必须返回统一错误 envelope。
invalidUploadRequest := httptest.NewRequest(http.MethodPost, "/api/v1/cards/batch", strings.NewReader("--openapi--\r\n"))
invalidUploadRequest.Header.Set("Content-Type", "multipart/form-data; boundary=openapi")
@@ -370,4 +612,37 @@ func TestOpenAPINotificationResponses(t *testing.T) {
bindingsRecorder := httptest.NewRecorder()
handler.ServeHTTP(bindingsRecorder, bindingsRequest)
assertOpenAPISuccessResponse(t, bindingsRequest, bindingsRecorder)
// createChannelRequest 是创建通知渠道的版本化成功请求,配置字段只使用测试占位值。
createChannelRequest := httptest.NewRequest(http.MethodPost, "/api/v1/notifications/channels", strings.NewReader(`{"name":"OpenAPI 渠道","type":"webhook","config":"{}","event_types":"[]","enabled":true}`))
createChannelRequest.AddCookie(sessionCookie)
// createChannelRecorder 捕获渠道创建返回的数值主键。
createChannelRecorder := httptest.NewRecorder()
handler.ServeHTTP(createChannelRecorder, createChannelRequest)
assertOpenAPISuccessResponse(t, createChannelRequest, createChannelRecorder)
// createdChannel 保存创建响应中的渠道标识。
var createdChannel struct {
// ID 是服务端分配的通知渠道主键。
ID int64 `json:"id"`
}
// channelDecodeErr 表示创建响应无法解析为具名主键 DTO 的失败原因。
if channelDecodeErr := json.Unmarshal(createChannelRecorder.Body.Bytes(), &createdChannel); channelDecodeErr != nil || createdChannel.ID <= 0 {
t.Fatalf("读取通知渠道标识失败: id=%d err=%v", createdChannel.ID, channelDecodeErr)
}
// channelID 是通知渠道路径参数的稳定字符串形式。
channelID := strconv.FormatInt(createdChannel.ID, 10)
// updateChannelRequest 是仅切换启用状态的部分更新成功请求。
updateChannelRequest := httptest.NewRequest(http.MethodPut, "/api/v1/notifications/channels/"+channelID, strings.NewReader(`{"enabled":false}`))
updateChannelRequest.AddCookie(sessionCookie)
// updateChannelRecorder 捕获渠道更新成功响应。
updateChannelRecorder := httptest.NewRecorder()
handler.ServeHTTP(updateChannelRecorder, updateChannelRequest)
assertOpenAPISuccessResponse(t, updateChannelRequest, updateChannelRecorder)
// deleteChannelRequest 是删除已归属通知渠道的成功请求。
deleteChannelRequest := httptest.NewRequest(http.MethodDelete, "/api/v1/notifications/channels/"+channelID, nil)
deleteChannelRequest.AddCookie(sessionCookie)
// deleteChannelRecorder 捕获渠道删除成功响应。
deleteChannelRecorder := httptest.NewRecorder()
handler.ServeHTTP(deleteChannelRecorder, deleteChannelRequest)
assertOpenAPISuccessResponse(t, deleteChannelRequest, deleteChannelRecorder)
}
+10
View File
@@ -735,6 +735,16 @@ func TestDownloadItemPublishBatchResultExportsRows(t *testing.T) {
if !strings.HasPrefix(body, "\xEF\xBB\xBF") || !strings.Contains(body, "行号") || !strings.Contains(body, "商品A") || !strings.Contains(body, "item-1") {
t.Fatalf("导出 CSV 内容异常: %q", body)
}
// versionedRequest 使用与旧入口相同的已完成批次,验证二进制特殊 operation 的真实成功响应。
versionedRequest := httptest.NewRequest(http.MethodGet, "/api/v1/items/publish-batches/"+batchID+"/result.csv", nil)
versionedRequest.AddCookie(cookie)
// versionedRecorder 捕获版本化 CSV 下载响应,供 OpenAPI 校验状态、Content-Type 与二进制 schema。
versionedRecorder := httptest.NewRecorder()
h.ServeHTTP(versionedRecorder, versionedRequest)
assertOpenAPISuccessResponse(t, versionedRequest, versionedRecorder)
if !strings.HasPrefix(versionedRecorder.Header().Get("Content-Type"), "text/csv") {
t.Fatalf("版本化 CSV Content-Type=%q", versionedRecorder.Header().Get("Content-Type"))
}
}
// TestDownloadItemPublishBatchResultHidesOtherUserBatch 验证结果下载不会泄露其他用户的批次存在性。
+160 -34
View File
@@ -8,6 +8,8 @@ import (
"strconv"
"strings"
"testing"
"xianyu-go/internal/db"
)
// TestNamedSuccessResponseContracts 验证认证、订单和聊天主链路使用具名成功响应 DTO。
@@ -16,7 +18,7 @@ func TestNamedSuccessResponseContracts(t *testing.T) {
srv, _, cleanup := newTestServer(t)
defer cleanup()
// handler 是当前测试使用的完整路由树。
handler := srv.Router()
handler := contractRecordingHandler(t, srv.Router())
// sessionCookie 是管理员登录后得到的认证会话。
sessionCookie := loginHelper(t, handler)
@@ -84,7 +86,7 @@ func TestRemainingSuccessResponseContracts(t *testing.T) {
srv, store, cleanup := newTestServer(t)
defer cleanup()
// handler 是当前测试使用的完整路由树。
handler := srv.Router()
handler := contractRecordingHandler(t, srv.Router())
// sessionCookie 是管理员登录后得到的认证会话。
sessionCookie := loginHelper(t, handler)
// seedErr 是测试商品写入模板数据库失败的原因。
@@ -195,12 +197,12 @@ func TestSettingsCardsNotificationsBatchContracts(t *testing.T) {
srv, _, cleanup := newTestServer(t)
defer cleanup()
// handler 是当前测试使用的完整路由树。
handler := srv.Router()
handler := contractRecordingHandler(t, srv.Router())
// sessionCookie 是管理员登录后得到的认证会话。
sessionCookie := loginHelper(t, handler)
// settingReq 是更新单个系统设置的请求。
settingReq := httptest.NewRequest(http.MethodPut, "/system-settings/theme_color", strings.NewReader(`{"value":"contract-blue"}`))
settingReq := httptest.NewRequest(http.MethodPut, "/api/v1/settings/system/theme_color", strings.NewReader(`{"value":"contract-blue"}`))
settingReq.AddCookie(sessionCookie)
// settingRecorder 是捕获系统设置响应的记录器。
settingRecorder := httptest.NewRecorder()
@@ -219,7 +221,7 @@ func TestSettingsCardsNotificationsBatchContracts(t *testing.T) {
}
// aiReq 是更新账号 AI 回复设置的请求。
aiReq := httptest.NewRequest(http.MethodPut, "/ai-reply-settings/acc1", strings.NewReader(`{"ai_enabled":true,"max_discount_percent":12,"max_discount_amount":88,"max_bargain_rounds":4,"custom_prompts":"契约测试"}`))
aiReq := httptest.NewRequest(http.MethodPut, "/api/v1/settings/ai-reply/acc1", strings.NewReader(`{"ai_enabled":true,"max_discount_percent":12,"max_discount_amount":88,"max_bargain_rounds":4,"custom_prompts":"契约测试"}`))
aiReq.AddCookie(sessionCookie)
// aiRecorder 是捕获账号 AI 设置响应的记录器。
aiRecorder := httptest.NewRecorder()
@@ -238,7 +240,7 @@ func TestSettingsCardsNotificationsBatchContracts(t *testing.T) {
}
// aiGetReq 是读取账号 AI 设置的请求。
aiGetReq := httptest.NewRequest(http.MethodGet, "/ai-reply-settings/acc1", nil)
aiGetReq := httptest.NewRequest(http.MethodGet, "/api/v1/settings/ai-reply/acc1", nil)
aiGetReq.AddCookie(sessionCookie)
// aiGetRecorder 是捕获账号 AI 设置查询响应的记录器。
aiGetRecorder := httptest.NewRecorder()
@@ -257,7 +259,7 @@ func TestSettingsCardsNotificationsBatchContracts(t *testing.T) {
}
// cardReq 是创建文本卡券组的请求。
cardReq := httptest.NewRequest(http.MethodPost, "/cards", strings.NewReader(`{"name":"契约卡","type":"text","text_content":"CARD","enabled":true}`))
cardReq := httptest.NewRequest(http.MethodPost, "/api/v1/cards", strings.NewReader(`{"name":"契约卡","type":"text","text_content":"CARD","enabled":true}`))
cardReq.AddCookie(sessionCookie)
// cardRecorder 是捕获卡券创建响应的记录器。
cardRecorder := httptest.NewRecorder()
@@ -276,7 +278,7 @@ func TestSettingsCardsNotificationsBatchContracts(t *testing.T) {
}
// cardGetReq 是读取卡券详情的请求。
cardGetReq := httptest.NewRequest(http.MethodGet, "/cards/"+strconv.FormatInt(cardCreateResponse.ID, 10), nil)
cardGetReq := httptest.NewRequest(http.MethodGet, "/api/v1/cards/"+strconv.FormatInt(cardCreateResponse.ID, 10), nil)
cardGetReq.AddCookie(sessionCookie)
// cardGetRecorder 是捕获卡券详情响应的记录器。
cardGetRecorder := httptest.NewRecorder()
@@ -295,7 +297,7 @@ func TestSettingsCardsNotificationsBatchContracts(t *testing.T) {
}
// channelReq 是创建通知渠道的请求。
channelReq := httptest.NewRequest(http.MethodPost, "/notification-channels", strings.NewReader(`{"name":"契约通知","type":"bark","config":"{}","enabled":true}`))
channelReq := httptest.NewRequest(http.MethodPost, "/api/v1/notifications/channels", strings.NewReader(`{"name":"契约通知","type":"bark","config":"{}","enabled":true}`))
channelReq.AddCookie(sessionCookie)
// channelRecorder 是捕获通知渠道创建响应的记录器。
channelRecorder := httptest.NewRecorder()
@@ -314,7 +316,7 @@ func TestSettingsCardsNotificationsBatchContracts(t *testing.T) {
}
// bindingReq 是将通知渠道绑定到测试账号的请求。
bindingReq := httptest.NewRequest(http.MethodPost, "/message-notifications/acc1", strings.NewReader(`{"channel_ids":[`+strconv.FormatInt(channelResponse.ID, 10)+`]}`))
bindingReq := httptest.NewRequest(http.MethodPost, "/api/v1/notifications/accounts/acc1/bindings", strings.NewReader(`{"channel_ids":[`+strconv.FormatInt(channelResponse.ID, 10)+`]}`))
bindingReq.AddCookie(sessionCookie)
// bindingRecorder 是捕获通知绑定响应的记录器。
bindingRecorder := httptest.NewRecorder()
@@ -333,7 +335,7 @@ func TestSettingsCardsNotificationsBatchContracts(t *testing.T) {
}
// bindingGetReq 是读取账号通知绑定的请求。
bindingGetReq := httptest.NewRequest(http.MethodGet, "/message-notifications/acc1", nil)
bindingGetReq := httptest.NewRequest(http.MethodGet, "/api/v1/notifications/accounts/acc1/bindings", nil)
bindingGetReq.AddCookie(sessionCookie)
// bindingGetRecorder 是捕获账号通知绑定响应的记录器。
bindingGetRecorder := httptest.NewRecorder()
@@ -352,7 +354,7 @@ func TestSettingsCardsNotificationsBatchContracts(t *testing.T) {
}
// batchReq 是读取商品批量任务列表的请求。
batchReq := httptest.NewRequest(http.MethodGet, "/items/publish-batches?limit=10", nil)
batchReq := httptest.NewRequest(http.MethodGet, "/api/v1/items/publish-batches?limit=10", nil)
batchReq.AddCookie(sessionCookie)
// batchRecorder 是捕获商品批量任务列表响应的记录器。
batchRecorder := httptest.NewRecorder()
@@ -377,12 +379,12 @@ func TestDynamicCompatibilitySuccessContracts(t *testing.T) {
srv, store, cleanup := newTestServer(t)
defer cleanup()
// handler 是当前测试使用的完整路由树。
handler := srv.Router()
handler := contractRecordingHandler(t, srv.Router())
// sessionCookie 是管理员登录后得到的认证会话。
sessionCookie := loginHelper(t, handler)
// publicSettingsReq 是读取公开系统设置的请求。
publicSettingsReq := httptest.NewRequest(http.MethodGet, "/system-settings/public", nil)
publicSettingsReq := httptest.NewRequest(http.MethodGet, "/api/v1/settings/system/public", nil)
// publicSettingsRecorder 是捕获公开设置响应的记录器。
publicSettingsRecorder := httptest.NewRecorder()
handler.ServeHTTP(publicSettingsRecorder, publicSettingsReq)
@@ -400,7 +402,7 @@ func TestDynamicCompatibilitySuccessContracts(t *testing.T) {
}
// allSettingsReq 是读取管理员系统设置的请求。
allSettingsReq := httptest.NewRequest(http.MethodGet, "/system-settings", nil)
allSettingsReq := httptest.NewRequest(http.MethodGet, "/api/v1/settings/system", nil)
allSettingsReq.AddCookie(sessionCookie)
// allSettingsRecorder 是捕获管理员设置响应的记录器。
allSettingsRecorder := httptest.NewRecorder()
@@ -419,7 +421,7 @@ func TestDynamicCompatibilitySuccessContracts(t *testing.T) {
}
// userSettingsReq 是读取当前用户设置的请求。
userSettingsReq := httptest.NewRequest(http.MethodGet, "/user-settings", nil)
userSettingsReq := httptest.NewRequest(http.MethodGet, "/api/v1/settings/user", nil)
userSettingsReq.AddCookie(sessionCookie)
// userSettingsRecorder 是捕获用户设置响应的记录器。
userSettingsRecorder := httptest.NewRecorder()
@@ -450,7 +452,7 @@ func TestDynamicCompatibilitySuccessContracts(t *testing.T) {
statusSessionID := "contract-qr"
ownQRSession(t, srv, store, statusSessionID)
// qrStatusReq 是读取二维码状态的请求。
qrStatusReq := httptest.NewRequest(http.MethodGet, "/qr-login/check/"+statusSessionID, nil)
qrStatusReq := httptest.NewRequest(http.MethodGet, "/api/v1/qr-login/check/"+statusSessionID, nil)
qrStatusReq.AddCookie(sessionCookie)
// qrStatusRecorder 是捕获二维码状态响应的记录器。
qrStatusRecorder := httptest.NewRecorder()
@@ -488,7 +490,7 @@ func TestDynamicCompatibilitySuccessContracts(t *testing.T) {
completeSessionID := "contract-complete"
ownQRSession(t, srv, store, completeSessionID)
// completeReq 是提交二维码风控验证完成的请求。
completeReq := httptest.NewRequest(http.MethodPost, "/qr-login/complete-verification/"+completeSessionID, nil)
completeReq := httptest.NewRequest(http.MethodPost, "/api/v1/qr-login/complete-verification/"+completeSessionID, nil)
completeReq.AddCookie(sessionCookie)
// completeRecorder 是捕获验证完成响应的记录器。
completeRecorder := httptest.NewRecorder()
@@ -513,12 +515,12 @@ func TestReplyAndAccountTaskSuccessResponseContracts(t *testing.T) {
srv, _, cleanup := newTestServer(t)
defer cleanup()
// handler 是当前测试使用的完整路由树。
handler := srv.Router()
handler := contractRecordingHandler(t, srv.Router())
// sessionCookie 是管理员登录后得到的认证会话。
sessionCookie := loginHelper(t, handler)
// keywordReq 是创建带商品范围关键词的请求。
keywordReq := httptest.NewRequest(http.MethodPost, "/keywords-with-item-id/acc1", strings.NewReader(`{"keyword":"契约关键词","reply":"契约回复","item_id":"contract-item"}`))
keywordReq := httptest.NewRequest(http.MethodPost, "/api/v1/reply-rules/acc1/items", strings.NewReader(`{"keyword":"契约关键词","reply":"契约回复","item_id":"contract-item"}`))
keywordReq.Header.Set("Content-Type", "application/json")
keywordReq.AddCookie(sessionCookie)
// keywordRecorder 是捕获关键词创建响应的记录器。
@@ -538,7 +540,7 @@ func TestReplyAndAccountTaskSuccessResponseContracts(t *testing.T) {
}
// keywordListReq 是读取带类型关键词列表的请求。
keywordListReq := httptest.NewRequest(http.MethodGet, "/keywords-with-type/acc1", nil)
keywordListReq := httptest.NewRequest(http.MethodGet, "/api/v1/reply-rules/acc1/typed", nil)
keywordListReq.AddCookie(sessionCookie)
// keywordListRecorder 是捕获关键词列表响应的记录器。
keywordListRecorder := httptest.NewRecorder()
@@ -557,7 +559,7 @@ func TestReplyAndAccountTaskSuccessResponseContracts(t *testing.T) {
}
// itemReplyReq 是保存指定商品回复的请求。
itemReplyReq := httptest.NewRequest(http.MethodPut, "/item-reply/acc1/contract-item", strings.NewReader(`{"reply_content":"商品契约回复"}`))
itemReplyReq := httptest.NewRequest(http.MethodPut, "/api/v1/reply-rules/items/acc1/contract-item", strings.NewReader(`{"reply_content":"商品契约回复"}`))
itemReplyReq.Header.Set("Content-Type", "application/json")
itemReplyReq.AddCookie(sessionCookie)
// itemReplyRecorder 是捕获指定商品回复响应的记录器。
@@ -577,7 +579,7 @@ func TestReplyAndAccountTaskSuccessResponseContracts(t *testing.T) {
}
// defaultReplyReq 是保存默认回复的请求。
defaultReplyReq := httptest.NewRequest(http.MethodPut, "/api/default-reply/acc1", strings.NewReader(`{"enabled":true,"reply_content":"默认契约回复","reply_once":true,"reply_image_url":""}`))
defaultReplyReq := httptest.NewRequest(http.MethodPut, "/api/v1/default-replies/acc1", strings.NewReader(`{"enabled":true,"reply_content":"默认契约回复","reply_once":true,"reply_image_url":""}`))
defaultReplyReq.Header.Set("Content-Type", "application/json")
defaultReplyReq.AddCookie(sessionCookie)
// defaultReplyRecorder 是捕获默认回复响应的记录器。
@@ -597,7 +599,7 @@ func TestReplyAndAccountTaskSuccessResponseContracts(t *testing.T) {
}
// defaultReplyGetReq 是读取默认回复的请求。
defaultReplyGetReq := httptest.NewRequest(http.MethodGet, "/api/default-reply/acc1", nil)
defaultReplyGetReq := httptest.NewRequest(http.MethodGet, "/api/v1/default-replies/acc1", nil)
defaultReplyGetReq.AddCookie(sessionCookie)
// defaultReplyGetRecorder 是捕获默认回复查询响应的记录器。
defaultReplyGetRecorder := httptest.NewRecorder()
@@ -616,7 +618,7 @@ func TestReplyAndAccountTaskSuccessResponseContracts(t *testing.T) {
}
// taskSettingsReq 是读取账号任务设置的请求。
taskSettingsReq := httptest.NewRequest(http.MethodGet, "/api/account-tasks/acc1", nil)
taskSettingsReq := httptest.NewRequest(http.MethodGet, "/api/v1/account-tasks/acc1", nil)
taskSettingsReq.AddCookie(sessionCookie)
// taskSettingsRecorder 是捕获账号任务设置响应的记录器。
taskSettingsRecorder := httptest.NewRecorder()
@@ -635,7 +637,7 @@ func TestReplyAndAccountTaskSuccessResponseContracts(t *testing.T) {
}
// taskRunsReq 是读取账号任务执行记录的请求。
taskRunsReq := httptest.NewRequest(http.MethodGet, "/api/account-tasks/acc1/runs", nil)
taskRunsReq := httptest.NewRequest(http.MethodGet, "/api/v1/account-tasks/acc1/runs", nil)
taskRunsReq.AddCookie(sessionCookie)
// taskRunsRecorder 是捕获账号任务执行记录响应的记录器。
taskRunsRecorder := httptest.NewRecorder()
@@ -660,7 +662,7 @@ func TestAnalyticsAdminAndPublicSuccessResponseContracts(t *testing.T) {
srv, store, cleanup := newTestServer(t)
defer cleanup()
// handler 是当前测试使用的完整路由树。
handler := srv.Router()
handler := contractRecordingHandler(t, srv.Router())
// sessionCookie 是管理员登录后得到的认证会话。
sessionCookie := loginHelper(t, handler)
// seedErr 是统计测试订单写入失败的原因。
@@ -669,7 +671,7 @@ func TestAnalyticsAdminAndPublicSuccessResponseContracts(t *testing.T) {
}
// adminStatsReq 是读取管理员全局统计的请求。
adminStatsReq := httptest.NewRequest(http.MethodGet, "/admin/stats", nil)
adminStatsReq := httptest.NewRequest(http.MethodGet, "/api/v1/admin/stats", nil)
adminStatsReq.AddCookie(sessionCookie)
// adminStatsRecorder 是捕获管理员统计响应的记录器。
adminStatsRecorder := httptest.NewRecorder()
@@ -688,7 +690,7 @@ func TestAnalyticsAdminAndPublicSuccessResponseContracts(t *testing.T) {
}
// adminUsersReq 是读取管理员用户列表的请求。
adminUsersReq := httptest.NewRequest(http.MethodGet, "/admin/users", nil)
adminUsersReq := httptest.NewRequest(http.MethodGet, "/api/v1/admin/users", nil)
adminUsersReq.AddCookie(sessionCookie)
// adminUsersRecorder 是捕获管理员用户列表响应的记录器。
adminUsersRecorder := httptest.NewRecorder()
@@ -707,7 +709,7 @@ func TestAnalyticsAdminAndPublicSuccessResponseContracts(t *testing.T) {
}
// adminCookiesReq 是读取管理员账号列表的请求。
adminCookiesReq := httptest.NewRequest(http.MethodGet, "/admin/cookies", nil)
adminCookiesReq := httptest.NewRequest(http.MethodGet, "/api/v1/admin/cookies", nil)
adminCookiesReq.AddCookie(sessionCookie)
// adminCookiesRecorder 是捕获管理员账号列表响应的记录器。
adminCookiesRecorder := httptest.NewRecorder()
@@ -726,7 +728,7 @@ func TestAnalyticsAdminAndPublicSuccessResponseContracts(t *testing.T) {
}
// dashboardReq 是读取当前用户概览统计的请求。
dashboardReq := httptest.NewRequest(http.MethodGet, "/dashboard/stats", nil)
dashboardReq := httptest.NewRequest(http.MethodGet, "/api/v1/analytics/dashboard", nil)
dashboardReq.AddCookie(sessionCookie)
// dashboardRecorder 是捕获概览统计响应的记录器。
dashboardRecorder := httptest.NewRecorder()
@@ -745,7 +747,7 @@ func TestAnalyticsAdminAndPublicSuccessResponseContracts(t *testing.T) {
}
// analyticsReq 是读取订单分析统计的请求。
analyticsReq := httptest.NewRequest(http.MethodGet, "/analytics/orders?start_date=2026-08-14&end_date=2026-08-14", nil)
analyticsReq := httptest.NewRequest(http.MethodGet, "/api/v1/analytics/orders?start_date=2026-08-14&end_date=2026-08-14", nil)
analyticsReq.AddCookie(sessionCookie)
// analyticsRecorder 是捕获订单分析响应的记录器。
analyticsRecorder := httptest.NewRecorder()
@@ -764,7 +766,7 @@ func TestAnalyticsAdminAndPublicSuccessResponseContracts(t *testing.T) {
}
// validOrdersReq 是读取有效订单分页的请求。
validOrdersReq := httptest.NewRequest(http.MethodGet, "/analytics/orders/valid?start_date=2026-08-14&end_date=2026-08-14", nil)
validOrdersReq := httptest.NewRequest(http.MethodGet, "/api/v1/analytics/orders/valid?start_date=2026-08-14&end_date=2026-08-14", nil)
validOrdersReq.AddCookie(sessionCookie)
// validOrdersRecorder 是捕获有效订单响应的记录器。
validOrdersRecorder := httptest.NewRecorder()
@@ -785,7 +787,7 @@ func TestAnalyticsAdminAndPublicSuccessResponseContracts(t *testing.T) {
// 二维码生成使用测试专用平台替身。
setTestQRLogin(srv, &fakeQRLoginService{})
// qrReq 是生成扫码登录二维码的请求。
qrReq := httptest.NewRequest(http.MethodPost, "/qr-login/generate", nil)
qrReq := httptest.NewRequest(http.MethodPost, "/api/v1/qr-login/generate", nil)
qrReq.AddCookie(sessionCookie)
// qrRecorder 是捕获二维码生成响应的记录器。
qrRecorder := httptest.NewRecorder()
@@ -803,3 +805,127 @@ func TestAnalyticsAdminAndPublicSuccessResponseContracts(t *testing.T) {
t.Fatalf("qr response=%+v", qrResponse)
}
}
// TestOpenAPILocalResourceMutationResponses 验证会话、账号和管理员本地资源变更均有真实版本化成功响应。
func TestOpenAPILocalResourceMutationResponses(t *testing.T) {
// srv、store、cleanup 分别提供独立 HTTP 服务、测试数据库和资源释放责任。
srv, store, cleanup := newTestServer(t)
defer cleanup()
// handler 是全量 chi Router,所有请求均通过正式版本化路由执行。
handler := srv.Router()
// healthRecorder 保存无需认证的健康检查成功响应。
healthRecorder := serveOpenAPISuccess(t, handler, nil, http.MethodGet, "/health", "")
if healthRecorder.Code != http.StatusOK {
t.Fatalf("health status=%d body=%s", healthRecorder.Code, healthRecorder.Body.String())
}
// sessionCookie 是初始管理员会话,用于验证当前密码并执行账号管理操作。
sessionCookie := loginHelper(t, handler)
// passwordRecorder 保存当前用户修改密码后的成功响应;该操作会废弃旧会话。
passwordRecorder := serveOpenAPISuccess(t, handler, sessionCookie, http.MethodPost, "/api/v1/session/password", `{"current_password":"pw","new_password":"new-password"}`)
if passwordRecorder.Code != http.StatusOK {
t.Fatalf("change password status=%d body=%s", passwordRecorder.Code, passwordRecorder.Body.String())
}
// refreshedCookie 是使用新密码重新登录后的会话,后续操作不依赖已撤销的旧会话。
refreshedCookie := loginAsHelper(t, handler, "admin", "new-password")
// credentialsRecorder 保存管理员用户名更新成功响应;当前密码保持新密码以验证敏感输入仅在服务端处理。
credentialsRecorder := serveOpenAPISuccess(t, handler, refreshedCookie, http.MethodPut, "/api/v1/session/credentials", `{"current_password":"new-password","new_username":"admin-contract"}`)
if credentialsRecorder.Code != http.StatusOK {
t.Fatalf("update credentials status=%d body=%s", credentialsRecorder.Code, credentialsRecorder.Body.String())
}
// renamedCookie 是用户名变更后重新登录得到的会话,确保后续管理员操作使用当前身份。
renamedCookie := loginAsHelper(t, handler, "admin-contract", "new-password")
// adminPasswordRecorder 保存管理员密码变更成功响应,覆盖管理员专属密码 operation。
adminPasswordRecorder := serveOpenAPISuccess(t, handler, renamedCookie, http.MethodPost, "/api/v1/admin/password", `{"current_password":"new-password","new_password":"final-password"}`)
if adminPasswordRecorder.Code != http.StatusOK {
t.Fatalf("change admin password status=%d body=%s", adminPasswordRecorder.Code, adminPasswordRecorder.Body.String())
}
// finalCookie 是最终密码对应的管理员会话,供账号和用户删除生命周期使用。
finalCookie := loginAsHelper(t, handler, "admin-contract", "final-password")
// accountRecorder 保存新建可删除账号的成功响应;请求内 Cookie 只用于测试输入,响应不得返回该明文。
accountRecorder := serveOpenAPISuccess(t, handler, finalCookie, http.MethodPost, "/api/v1/accounts", `{"id":"delete-contract","value":"unb=delete-contract","login_method":"manual"}`)
if accountRecorder.Code != http.StatusOK || strings.Contains(accountRecorder.Body.String(), "unb=delete-contract") {
t.Fatalf("create account response invalid: status=%d body=%s", accountRecorder.Code, accountRecorder.Body.String())
}
// deleteAccountRecorder 保存同一账号的删除成功响应,形成真实账号资源生命周期闭环。
deleteAccountRecorder := serveOpenAPISuccess(t, handler, finalCookie, http.MethodDelete, "/api/v1/accounts/delete-contract", "")
if deleteAccountRecorder.Code != http.StatusOK {
t.Fatalf("delete account status=%d body=%s", deleteAccountRecorder.Code, deleteAccountRecorder.Body.String())
}
// created、createUserErr 分别表示普通用户是否已写入和创建失败原因。
created, createUserErr := store.Users.Create(context.Background(), "delete-user", "delete-user@example.com", "pw")
if createUserErr != nil {
t.Fatalf("create deletable user: %v", createUserErr)
}
if !created {
t.Fatal("create deletable user returned false")
}
// deletableUser、getUserErr 分别保存待删除普通用户的稳定数据库 ID 和重新读取失败原因。
deletableUser, getUserErr := store.Users.GetByUsername(context.Background(), "delete-user")
if getUserErr != nil || deletableUser == nil {
t.Fatalf("load deletable user: user=%+v err=%v", deletableUser, getUserErr)
}
// deleteUserRecorder 保存管理员删除普通用户的成功响应,避免把不存在用户的 4xx 当作成功证据。
deleteUserRecorder := serveOpenAPISuccess(t, handler, finalCookie, http.MethodDelete, "/api/v1/admin/users/"+strconv.FormatInt(deletableUser.ID, 10), "")
if deleteUserRecorder.Code != http.StatusOK {
t.Fatalf("delete user status=%d body=%s", deleteUserRecorder.Code, deleteUserRecorder.Body.String())
}
// automationCardID、automationCreateRecorder 分别保存自动化规则所需卡券 ID 和创建响应。
automationCardID, cardErr := store.Cards.Create(context.Background(), &db.CardFull{Name: "契约自动化卡", Type: "text", TextContent: "CARD", Enabled: true, UserID: 1})
if cardErr != nil {
t.Fatalf("create automation card: %v", cardErr)
}
// itemErr 表示自动化规则关联商品夹具写入失败。
if _, itemErr := store.DB.ExecContext(context.Background(), `INSERT INTO item_info (cookie_id, item_id, item_title) VALUES ('acc1','contract-automation-item','自动化商品')`); itemErr != nil {
t.Fatalf("create automation item: %v", itemErr)
}
// automationCreateRecorder 保存自动化规则创建成功响应。
automationCreateRecorder := serveOpenAPISuccess(t, handler, finalCookie, http.MethodPost, "/api/v1/automation-rules", `{"cookie_id":"acc1","item_id":"contract-automation-item","trigger_type":"order_paid","enabled":true,"actions":[{"action_type":"send_card","card_id":`+strconv.FormatInt(automationCardID, 10)+`,"delivery_count":1}]}`)
// automationCreateResponse 保存自动化规则创建返回的数值主键。
var automationCreateResponse mutationIDResponse
// decodeErr 表示解析自动化规则创建响应失败。
if decodeErr := json.Unmarshal(automationCreateRecorder.Body.Bytes(), &automationCreateResponse); decodeErr != nil || automationCreateResponse.ID == 0 {
t.Fatalf("decode automation create: id=%d err=%v body=%s", automationCreateResponse.ID, decodeErr, automationCreateRecorder.Body.String())
}
// automationRuleID 是后续更新和删除操作使用的规则路径标识。
automationRuleID := strconv.FormatInt(automationCreateResponse.ID, 10)
serveOpenAPISuccess(t, handler, finalCookie, http.MethodPut, "/api/v1/automation-rules/"+automationRuleID, `{"cookie_id":"acc1","item_id":"contract-automation-item","trigger_type":"order_paid","enabled":false,"actions":[{"action_type":"send_card","card_id":`+strconv.FormatInt(automationCardID, 10)+`,"delivery_count":1}]}`)
serveOpenAPISuccess(t, handler, finalCookie, http.MethodDelete, "/api/v1/automation-rules/"+automationRuleID, "")
serveOpenAPISuccess(t, handler, finalCookie, http.MethodPut, "/api/v1/default-replies/acc1", `{"enabled":true,"reply_content":"契约默认回复","reply_once":true}`)
serveOpenAPISuccess(t, handler, finalCookie, http.MethodGet, "/api/v1/default-replies/acc1", "")
serveOpenAPISuccess(t, handler, finalCookie, http.MethodGet, "/api/v1/default-replies", "")
serveOpenAPISuccess(t, handler, finalCookie, http.MethodGet, "/api/v1/default-replies/list", "")
serveOpenAPISuccess(t, handler, finalCookie, http.MethodPost, "/api/v1/default-replies/acc1/clear-records", "{}")
serveOpenAPISuccess(t, handler, finalCookie, http.MethodDelete, "/api/v1/default-replies/acc1", "")
serveOpenAPISuccess(t, handler, finalCookie, http.MethodGet, "/api/v1/items/cookie/acc1", "")
serveOpenAPISuccess(t, handler, finalCookie, http.MethodGet, "/api/v1/items/publish-batches", "")
serveOpenAPISuccess(t, handler, finalCookie, http.MethodGet, "/api/v1/cards/1/details", "")
// orderID 是用于删除订单成功场景的本地订单标识。
orderID := "contract-delete-order"
// orderErr 表示订单删除成功场景夹具写入失败。
if _, orderErr := store.DB.ExecContext(context.Background(), `INSERT INTO orders (order_id,item_id,buyer_id,order_status,cookie_id) VALUES ('contract-delete-order','contract-automation-item','buyer','pending_ship','acc1')`); orderErr != nil {
t.Fatalf("create delete order: %v", orderErr)
}
serveOpenAPISuccess(t, handler, finalCookie, http.MethodDelete, "/api/v1/orders/"+orderID, "")
serveOpenAPISuccess(t, handler, finalCookie, http.MethodPut, "/api/v1/items/acc1/contract-automation-item/multi-spec", `{"enabled":true}`)
serveOpenAPISuccess(t, handler, finalCookie, http.MethodPut, "/api/v1/items/acc1/contract-automation-item/multi-quantity-delivery", `{"enabled":true}`)
// keywordRecorder 保存普通关键词规则创建成功响应,后续通过带类型列表获取稳定 ID。
keywordRecorder := serveOpenAPISuccess(t, handler, finalCookie, http.MethodPost, "/api/v1/reply-rules/acc1", `{"keyword":"契约关键字","reply":"契约回复"}`)
if keywordRecorder.Code != http.StatusOK {
t.Fatalf("create keyword status=%d body=%s", keywordRecorder.Code, keywordRecorder.Body.String())
}
// keywordListRecorder 保存带类型关键词列表成功响应。
keywordListRecorder := serveOpenAPISuccess(t, handler, finalCookie, http.MethodGet, "/api/v1/reply-rules/acc1/typed", "")
// keywordRows 保存带稳定数值主键的关键词规则集合。
var keywordRows []keywordTypedResponse
// keywordListErr 表示解析带类型关键词列表失败。
if keywordListErr := json.Unmarshal(keywordListRecorder.Body.Bytes(), &keywordRows); keywordListErr != nil || len(keywordRows) == 0 {
t.Fatalf("load typed keywords: rows=%+v err=%v", keywordRows, keywordListErr)
}
// keywordID 是当前创建规则的稳定主键,用于更新、按 ID 删除与按索引删除的成功场景。
keywordID := strconv.FormatInt(keywordRows[0].ID, 10)
serveOpenAPISuccess(t, handler, finalCookie, http.MethodPut, "/api/v1/reply-rules/acc1/typed/"+keywordID, `{"keyword":"契约关键字","reply":"已更新回复","type":"text"}`)
serveOpenAPISuccess(t, handler, finalCookie, http.MethodDelete, "/api/v1/reply-rules/acc1/typed/"+keywordID, "")
serveOpenAPISuccess(t, handler, finalCookie, http.MethodPost, "/api/v1/reply-rules/acc1", `{"keyword":"索引关键字","reply":"索引回复"}`)
serveOpenAPISuccess(t, handler, finalCookie, http.MethodDelete, "/api/v1/reply-rules/acc1/index/0", "")
serveOpenAPISuccess(t, handler, finalCookie, http.MethodPut, "/api/v1/account-tasks/acc1", `{"auto_rate_enabled":true,"rate_content":"服务很好","auto_polish_enabled":false,"polish_time":"03:00"}`)
}
+10
View File
@@ -62,6 +62,16 @@ func TestChatEventDTOUsesFrontendContract(t *testing.T) {
if loadErr != nil {
t.Fatalf("加载 OpenAPI WebSocket 契约: %v", loadErr)
}
// webSocketPath 是版本化聊天 WebSocket operation 的 OpenAPI 路径定义。
webSocketPath := document.Paths.Find("/api/v1/chat/ws")
if webSocketPath == nil || webSocketPath.Get == nil || webSocketPath.Get.Responses == nil || webSocketPath.Get.Responses.Value("101") == nil {
t.Fatal("OpenAPI 缺少聊天 WebSocket 101 升级响应")
}
// rawException、exceptionOK 分别是成功响应特殊校验扩展原值及其对象结构是否有效。
rawException, exceptionOK := webSocketPath.Get.Extensions["x-contract-success-exception"].(map[string]any)
if !exceptionOK || rawException["kind"] != "websocket" {
t.Fatalf("聊天 WebSocket 未登记 websocket 特殊校验: %#v", webSocketPath.Get.Extensions["x-contract-success-exception"])
}
// eventSchemaRef 保存 WebSocket 推送帧的具名 schema 引用。
eventSchemaRef := document.Components.Schemas["ChatWebSocketEvent"]
if eventSchemaRef == nil || eventSchemaRef.Value == nil {
+2
View File
@@ -21,6 +21,8 @@ var (
serverTestTemplatePath string
// serverTestTemplateErr 保存创建共享模板时遇到的错误。
serverTestTemplateErr error
// openAPISuccessOperations 收集当前 Go 测试进程中经真实 Router 成功响应校验的 operationId。
openAPISuccessOperations sync.Map
)
// TestMain 在所有 server 测试结束后删除共享数据库模板目录。
@@ -27,9 +27,7 @@ func TestVersionedAccountRoutesPreserveLegacyContracts(t *testing.T) {
// listRecorder 是捕获账号摘要响应的记录器。
listRecorder := httptest.NewRecorder()
handler.ServeHTTP(listRecorder, listReq)
if listRecorder.Code != http.StatusOK {
t.Fatalf("versioned account list status=%d body=%s", listRecorder.Code, listRecorder.Body.String())
}
assertOpenAPISuccessResponse(t, listReq, listRecorder)
// accountIDs 是版本化账号摘要 ID 列表。
var accountIDs []string
// listDecodeErr 是账号摘要响应反序列化失败的原因。
@@ -46,9 +44,7 @@ func TestVersionedAccountRoutesPreserveLegacyContracts(t *testing.T) {
// detailsRecorder 是捕获账号详情响应的记录器。
detailsRecorder := httptest.NewRecorder()
handler.ServeHTTP(detailsRecorder, detailsReq)
if detailsRecorder.Code != http.StatusOK {
t.Fatalf("versioned account details status=%d body=%s", detailsRecorder.Code, detailsRecorder.Body.String())
}
assertOpenAPISuccessResponse(t, detailsReq, detailsRecorder)
// detailsValue 是版本化账号详情 DTO 集合。
var detailsValue []cookieSummaryResponse
// detailsDecodeErr 是账号详情响应反序列化失败的原因。
@@ -68,9 +64,7 @@ func TestVersionedAccountRoutesPreserveLegacyContracts(t *testing.T) {
// runtimeRecorder 是捕获账号运行状态响应的记录器。
runtimeRecorder := httptest.NewRecorder()
handler.ServeHTTP(runtimeRecorder, runtimeReq)
if runtimeRecorder.Code != http.StatusOK {
t.Fatalf("versioned runtime status=%d body=%s", runtimeRecorder.Code, runtimeRecorder.Body.String())
}
assertOpenAPISuccessResponse(t, runtimeReq, runtimeRecorder)
// runtimeValue 是版本化账号运行状态映射。
var runtimeValue map[string]engine.RuntimeStatus
// runtimeDecodeErr 是运行状态响应反序列化失败的原因。
@@ -87,9 +81,7 @@ func TestVersionedAccountRoutesPreserveLegacyContracts(t *testing.T) {
// detailRecorder 是捕获单账号详情响应的记录器。
detailRecorder := httptest.NewRecorder()
handler.ServeHTTP(detailRecorder, detailReq)
if detailRecorder.Code != http.StatusOK {
t.Fatalf("versioned account detail status=%d body=%s", detailRecorder.Code, detailRecorder.Body.String())
}
assertOpenAPISuccessResponse(t, detailReq, detailRecorder)
// detailValue 是版本化单账号详情 DTO。
var detailValue cookieDetailResponse
// detailDecodeErr 是单账号详情响应反序列化失败的原因。
@@ -106,9 +98,7 @@ func TestVersionedAccountRoutesPreserveLegacyContracts(t *testing.T) {
// statusRecorder 是捕获账号状态变更响应的记录器。
statusRecorder := httptest.NewRecorder()
handler.ServeHTTP(statusRecorder, statusReq)
if statusRecorder.Code != http.StatusOK {
t.Fatalf("versioned account status=%d body=%s", statusRecorder.Code, statusRecorder.Body.String())
}
assertOpenAPISuccessResponse(t, statusReq, statusRecorder)
// statusValue 是账号状态变更具名响应 DTO。
var statusValue operationResponse
// statusDecodeErr 是状态变更响应反序列化失败的原因。
@@ -157,9 +147,7 @@ func TestVersionedAccountCredentialRoutesPreserveLegacyContracts(t *testing.T) {
// addRecorder 是捕获新增账号响应的记录器。
addRecorder := httptest.NewRecorder()
handler.ServeHTTP(addRecorder, addReq)
if addRecorder.Code != http.StatusOK {
t.Fatalf("versioned add account status=%d body=%s", addRecorder.Code, addRecorder.Body.String())
}
assertOpenAPISuccessResponse(t, addReq, addRecorder)
// addValue 是新增账号响应中的具名结果 DTO。
var addValue accountMutationResponse
// addDecodeErr 是新增账号响应反序列化失败的原因。
@@ -179,9 +167,7 @@ func TestVersionedAccountCredentialRoutesPreserveLegacyContracts(t *testing.T) {
// updateRecorder 是捕获 Cookie 更新响应的记录器。
updateRecorder := httptest.NewRecorder()
handler.ServeHTTP(updateRecorder, updateReq)
if updateRecorder.Code != http.StatusOK {
t.Fatalf("versioned update account status=%d body=%s", updateRecorder.Code, updateRecorder.Body.String())
}
assertOpenAPISuccessResponse(t, updateReq, updateRecorder)
// updateValue 是 Cookie 更新响应中的具名结果 DTO。
var updateValue operationResponse
// updateDecodeErr 是 Cookie 更新响应反序列化失败的原因。
@@ -201,9 +187,7 @@ func TestVersionedAccountCredentialRoutesPreserveLegacyContracts(t *testing.T) {
// loginInfoRecorder 是捕获登录信息更新响应的记录器。
loginInfoRecorder := httptest.NewRecorder()
handler.ServeHTTP(loginInfoRecorder, loginInfoReq)
if loginInfoRecorder.Code != http.StatusOK {
t.Fatalf("versioned login info status=%d body=%s", loginInfoRecorder.Code, loginInfoRecorder.Body.String())
}
assertOpenAPISuccessResponse(t, loginInfoReq, loginInfoRecorder)
// loginInfoValue 是登录信息更新响应中的具名结果 DTO。
var loginInfoValue operationResponse
// loginInfoDecodeErr 是登录信息响应反序列化失败的原因。
@@ -250,9 +234,7 @@ func TestVersionedAccountSettingsRoutesPreserveLegacyContracts(t *testing.T) {
// settingsRecorder 是捕获聚合设置响应的记录器。
settingsRecorder := httptest.NewRecorder()
handler.ServeHTTP(settingsRecorder, settingsReq)
if settingsRecorder.Code != http.StatusOK {
t.Fatalf("versioned settings status=%d body=%s", settingsRecorder.Code, settingsRecorder.Body.String())
}
assertOpenAPISuccessResponse(t, settingsReq, settingsRecorder)
// settingsValue 是聚合账号设置具名响应 DTO。
var settingsValue cookieSettingsResponse
// settingsDecodeErr 是聚合设置响应反序列化失败的原因。
@@ -269,9 +251,7 @@ func TestVersionedAccountSettingsRoutesPreserveLegacyContracts(t *testing.T) {
// remarkRecorder 是捕获备注响应的记录器。
remarkRecorder := httptest.NewRecorder()
handler.ServeHTTP(remarkRecorder, remarkReq)
if remarkRecorder.Code != http.StatusOK {
t.Fatalf("versioned remark status=%d body=%s", remarkRecorder.Code, remarkRecorder.Body.String())
}
assertOpenAPISuccessResponse(t, remarkReq, remarkRecorder)
// remarkValue 是备注变更具名响应 DTO。
var remarkValue operationResponse
// remarkDecodeErr 是备注响应反序列化失败的原因。
@@ -288,9 +268,7 @@ func TestVersionedAccountSettingsRoutesPreserveLegacyContracts(t *testing.T) {
// autoConfirmRecorder 是捕获自动确认响应的记录器。
autoConfirmRecorder := httptest.NewRecorder()
handler.ServeHTTP(autoConfirmRecorder, autoConfirmReq)
if autoConfirmRecorder.Code != http.StatusOK {
t.Fatalf("versioned auto-confirm status=%d body=%s", autoConfirmRecorder.Code, autoConfirmRecorder.Body.String())
}
assertOpenAPISuccessResponse(t, autoConfirmReq, autoConfirmRecorder)
// pauseReq 是更新版本化暂停时长的请求。
pauseReq := httptest.NewRequest(http.MethodPut, "/api/v1/accounts/acc1/pause-duration", strings.NewReader(`{"pause_duration":15}`))
@@ -298,9 +276,7 @@ func TestVersionedAccountSettingsRoutesPreserveLegacyContracts(t *testing.T) {
// pauseRecorder 是捕获暂停时长响应的记录器。
pauseRecorder := httptest.NewRecorder()
handler.ServeHTTP(pauseRecorder, pauseReq)
if pauseRecorder.Code != http.StatusOK {
t.Fatalf("versioned pause status=%d body=%s", pauseRecorder.Code, pauseRecorder.Body.String())
}
assertOpenAPISuccessResponse(t, pauseReq, pauseRecorder)
// pauseValue 是暂停时长具名响应 DTO。
var pauseValue cookieSettingsResponse
// pauseDecodeErr 是暂停响应反序列化失败的原因。
@@ -317,9 +293,7 @@ func TestVersionedAccountSettingsRoutesPreserveLegacyContracts(t *testing.T) {
// autoConfirmGetRecorder 是捕获自动确认查询响应的记录器。
autoConfirmGetRecorder := httptest.NewRecorder()
handler.ServeHTTP(autoConfirmGetRecorder, autoConfirmGetReq)
if autoConfirmGetRecorder.Code != http.StatusOK {
t.Fatalf("versioned auto-confirm get status=%d body=%s", autoConfirmGetRecorder.Code, autoConfirmGetRecorder.Body.String())
}
assertOpenAPISuccessResponse(t, autoConfirmGetReq, autoConfirmGetRecorder)
// autoConfirmValue 是自动确认查询具名响应 DTO。
var autoConfirmValue autoConfirmResponse
// autoConfirmDecodeErr 是自动确认查询响应反序列化失败的原因。
@@ -336,9 +310,7 @@ func TestVersionedAccountSettingsRoutesPreserveLegacyContracts(t *testing.T) {
// pauseGetRecorder 是捕获暂停查询响应的记录器。
pauseGetRecorder := httptest.NewRecorder()
handler.ServeHTTP(pauseGetRecorder, pauseGetReq)
if pauseGetRecorder.Code != http.StatusOK {
t.Fatalf("versioned pause get status=%d body=%s", pauseGetRecorder.Code, pauseGetRecorder.Body.String())
}
assertOpenAPISuccessResponse(t, pauseGetReq, pauseGetRecorder)
// pauseGetValue 是暂停查询具名响应 DTO。
var pauseGetValue pauseDurationResponse
// pauseGetDecodeErr 是暂停查询响应反序列化失败的原因。
@@ -355,9 +327,7 @@ func TestVersionedAccountSettingsRoutesPreserveLegacyContracts(t *testing.T) {
// profileRecorder 是捕获资料刷新响应的记录器。
profileRecorder := httptest.NewRecorder()
handler.ServeHTTP(profileRecorder, profileReq)
if profileRecorder.Code != http.StatusOK {
t.Fatalf("versioned profile status=%d body=%s", profileRecorder.Code, profileRecorder.Body.String())
}
assertOpenAPISuccessResponse(t, profileReq, profileRecorder)
// profileValue 是资料刷新具名响应 DTO。
var profileValue cookieProfileResponse
// profileDecodeErr 是资料刷新响应反序列化失败的原因。
@@ -33,6 +33,9 @@ func requestAdminAnalyticsRoute(t *testing.T, handler http.Handler, sessionCooki
// recorder 是捕获兼容入口响应的记录器。
recorder := httptest.NewRecorder()
handler.ServeHTTP(recorder, request)
if strings.HasPrefix(path, "/api/v1/") && recorder.Code >= http.StatusOK && recorder.Code < http.StatusMultipleChoices {
assertOpenAPIRecordedSuccessResponse(t, request, recorder)
}
return recorder.Code
}
@@ -32,6 +32,9 @@ func requestChatTaskRoute(t *testing.T, handler http.Handler, sessionCookie *htt
// recorder 是捕获兼容入口响应的记录器。
recorder := httptest.NewRecorder()
handler.ServeHTTP(recorder, request)
if strings.HasPrefix(path, "/api/v1/") && recorder.Code >= http.StatusOK && recorder.Code < http.StatusMultipleChoices {
assertOpenAPIRecordedSuccessResponse(t, request, recorder)
}
return recorder.Code
}
@@ -32,6 +32,9 @@ func requestItemBatchRoute(t *testing.T, handler http.Handler, sessionCookie *ht
// recorder 是捕获商品批量响应的记录器。
recorder := httptest.NewRecorder()
handler.ServeHTTP(recorder, request)
if strings.HasPrefix(path, "/api/v1/") && recorder.Code >= http.StatusOK && recorder.Code < http.StatusMultipleChoices {
assertOpenAPIRecordedSuccessResponse(t, request, recorder)
}
return recorder.Code
}
@@ -32,9 +32,7 @@ func TestVersionedItemRoutesPreserveLegacyContracts(t *testing.T) {
// listRecorder 是捕获版本化商品列表响应的记录器。
listRecorder := httptest.NewRecorder()
handler.ServeHTTP(listRecorder, listReq)
if listRecorder.Code != http.StatusOK {
t.Fatalf("versioned item list status=%d body=%s", listRecorder.Code, listRecorder.Body.String())
}
assertOpenAPISuccessResponse(t, listReq, listRecorder)
// listValue 是版本化商品列表响应 DTO 集合。
var listValue []itemListResponse
// listDecodeErr 是商品列表响应反序列化失败的原因。
@@ -51,9 +49,7 @@ func TestVersionedItemRoutesPreserveLegacyContracts(t *testing.T) {
// detailRecorder 是捕获版本化商品详情响应的记录器。
detailRecorder := httptest.NewRecorder()
handler.ServeHTTP(detailRecorder, detailReq)
if detailRecorder.Code != http.StatusOK {
t.Fatalf("versioned item detail status=%d body=%s", detailRecorder.Code, detailRecorder.Body.String())
}
assertOpenAPISuccessResponse(t, detailReq, detailRecorder)
// detailValue 是版本化商品详情响应 DTO。
var detailValue itemDetailResponse
// detailDecodeErr 是商品详情响应反序列化失败的原因。
@@ -70,9 +66,7 @@ func TestVersionedItemRoutesPreserveLegacyContracts(t *testing.T) {
// updateRecorder 是捕获版本化商品更新响应的记录器。
updateRecorder := httptest.NewRecorder()
handler.ServeHTTP(updateRecorder, updateReq)
if updateRecorder.Code != http.StatusOK {
t.Fatalf("versioned item update status=%d body=%s", updateRecorder.Code, updateRecorder.Body.String())
}
assertOpenAPISuccessResponse(t, updateReq, updateRecorder)
// updatedItem 是数据库中用于确认版本化更新结果的商品记录。
updatedItem, updatedErr := store.Items.Get(ctx, "acc1", "item-v1")
if updatedErr != nil || updatedItem == nil || updatedItem.ItemTitle != "版本化新商品名" {
@@ -95,9 +89,7 @@ func TestVersionedItemRoutesPreserveLegacyContracts(t *testing.T) {
// deleteRecorder 是捕获版本化商品删除响应的记录器。
deleteRecorder := httptest.NewRecorder()
handler.ServeHTTP(deleteRecorder, deleteReq)
if deleteRecorder.Code != http.StatusOK {
t.Fatalf("versioned item delete status=%d body=%s", deleteRecorder.Code, deleteRecorder.Body.String())
}
assertOpenAPISuccessResponse(t, deleteReq, deleteRecorder)
// legacyDeleteReq 是验证旧商品删除入口仍可用的请求。
legacyDeleteReq := httptest.NewRequest(http.MethodDelete, "/items/acc1/item-legacy", nil)
@@ -34,9 +34,7 @@ func TestVersionedOrderRoutesPreserveLegacyContracts(t *testing.T) {
// listRecorder 是捕获版本化订单列表响应的记录器。
listRecorder := httptest.NewRecorder()
handler.ServeHTTP(listRecorder, listReq)
if listRecorder.Code != http.StatusOK {
t.Fatalf("versioned order list status=%d body=%s", listRecorder.Code, listRecorder.Body.String())
}
assertOpenAPISuccessResponse(t, listReq, listRecorder)
// listValue 是版本化订单列表响应 DTO。
var listValue orderListResponse
// listDecodeErr 是订单列表响应反序列化失败的原因。
@@ -53,9 +51,7 @@ func TestVersionedOrderRoutesPreserveLegacyContracts(t *testing.T) {
// detailRecorder 是捕获版本化订单详情响应的记录器。
detailRecorder := httptest.NewRecorder()
handler.ServeHTTP(detailRecorder, detailReq)
if detailRecorder.Code != http.StatusOK {
t.Fatalf("versioned order detail status=%d body=%s", detailRecorder.Code, detailRecorder.Body.String())
}
assertOpenAPISuccessResponse(t, detailReq, detailRecorder)
// detailValue 是版本化订单详情响应 DTO。
var detailValue orderDetailResponse
// detailDecodeErr 是订单详情响应反序列化失败的原因。
@@ -72,9 +68,7 @@ func TestVersionedOrderRoutesPreserveLegacyContracts(t *testing.T) {
// updateRecorder 是捕获版本化订单更新响应的记录器。
updateRecorder := httptest.NewRecorder()
handler.ServeHTTP(updateRecorder, updateReq)
if updateRecorder.Code != http.StatusOK {
t.Fatalf("versioned order update status=%d body=%s", updateRecorder.Code, updateRecorder.Body.String())
}
assertOpenAPISuccessResponse(t, updateReq, updateRecorder)
// updateValue 是版本化订单更新响应 DTO。
var updateValue operationResponse
// updateDecodeErr 是订单更新响应反序列化失败的原因。
@@ -124,20 +118,38 @@ func TestVersionedOrderRefreshAndBatchRoutesPreserveLegacyContracts(t *testing.T
// refreshRecorder 是捕获版本化刷新响应的记录器。
refreshRecorder := httptest.NewRecorder()
handler.ServeHTTP(refreshRecorder, refreshReq)
if refreshRecorder.Code != http.StatusAccepted {
t.Fatalf("versioned order refresh status=%d body=%s", refreshRecorder.Code, refreshRecorder.Body.String())
}
assertOpenAPIExpectedStatusResponse(t, refreshReq, refreshRecorder, http.StatusAccepted)
// refreshStart 是版本化刷新任务创建响应 DTO。
var refreshStart orderRefreshJobStartResponse
// refreshDecodeErr 是刷新任务创建响应反序列化失败的原因。
if refreshDecodeErr := json.Unmarshal(refreshRecorder.Body.Bytes(), &refreshStart); refreshDecodeErr != nil {
t.Fatalf("decode versioned order refresh: %v", refreshDecodeErr)
}
// versionedStatusReq 查询刚创建的版本化刷新任务,覆盖真实 200 状态响应。
versionedStatusReq := httptest.NewRequest(http.MethodGet, "/api/v1/orders/refresh/"+refreshStart.JobID, nil)
versionedStatusReq.AddCookie(sessionCookie)
// versionedStatusRecorder 保存版本化刷新任务查询响应。
versionedStatusRecorder := httptest.NewRecorder()
handler.ServeHTTP(versionedStatusRecorder, versionedStatusReq)
assertOpenAPIRecordedSuccessResponse(t, versionedStatusReq, versionedStatusRecorder)
// refreshValue 是版本化刷新任务完成后的具名结果。
refreshValue := waitOrderRefreshJob(t, handler, sessionCookie, refreshStart.JobID)
if refreshValue.Message == "" {
t.Fatalf("versioned order refresh should preserve a named success response: %+v", refreshValue)
}
// queuedJob 是专门用于版本化取消 operation 的排队任务夹具。
queuedJob := &db.OrderRefreshJob{ID: "versioned-cancel-job", UserID: 1, Status: "queued"}
// createErr 表示写入版本化取消任务夹具失败。
if createErr := store.OrderRefreshJobs.Create(ctx, queuedJob); createErr != nil {
t.Fatalf("create versioned cancel job: %v", createErr)
}
// versionedCancelReq 请求取消该排队任务。
versionedCancelReq := httptest.NewRequest(http.MethodDelete, "/api/v1/orders/refresh/"+queuedJob.ID, nil)
versionedCancelReq.AddCookie(sessionCookie)
// versionedCancelRecorder 保存版本化取消响应。
versionedCancelRecorder := httptest.NewRecorder()
handler.ServeHTTP(versionedCancelRecorder, versionedCancelReq)
assertOpenAPIRecordedSuccessResponse(t, versionedCancelReq, versionedCancelRecorder)
// legacyRefreshReq 是验证旧订单列表刷新入口仍可用的请求。
legacyRefreshReq := httptest.NewRequest(http.MethodPost, "/api/orders/refresh", nil)
@@ -167,10 +179,7 @@ func TestVersionedOrderRefreshAndBatchRoutesPreserveLegacyContracts(t *testing.T
// singleRecorder 是捕获版本化单订单刷新响应的记录器。
singleRecorder := httptest.NewRecorder()
handler.ServeHTTP(singleRecorder, singleReq)
// 夹具客户端提供订单详情响应,新旧入口都应返回成功刷新结果。
if singleRecorder.Code != http.StatusOK {
t.Fatalf("versioned single order refresh status=%d body=%s", singleRecorder.Code, singleRecorder.Body.String())
}
assertOpenAPISuccessResponse(t, singleReq, singleRecorder)
// legacySingleReq 是验证旧单订单刷新入口仍可用的请求。
legacySingleReq := httptest.NewRequest(http.MethodPost, "/api/orders/order-single-v1/refresh", nil)
@@ -208,9 +217,7 @@ func TestVersionedOrderRefreshAndBatchRoutesPreserveLegacyContracts(t *testing.T
// importRecorder 是捕获版本化导入响应的记录器。
importRecorder := httptest.NewRecorder()
handler.ServeHTTP(importRecorder, importReq)
if importRecorder.Code != http.StatusOK {
t.Fatalf("versioned order import status=%d body=%s", importRecorder.Code, importRecorder.Body.String())
}
assertOpenAPISuccessResponse(t, importReq, importRecorder)
// legacyImportReq 是验证旧导入入口仍可用的请求。
legacyImportReq := httptest.NewRequest(http.MethodPost, "/api/orders/import", strings.NewReader(`[]`))
@@ -33,6 +33,9 @@ func requestQRLoginRoute(t *testing.T, handler http.Handler, sessionCookie *http
// recorder 是捕获二维码响应的测试记录器。
recorder := httptest.NewRecorder()
handler.ServeHTTP(recorder, request)
if strings.HasPrefix(path, "/api/v1/") && recorder.Code >= http.StatusOK && recorder.Code < http.StatusMultipleChoices {
assertOpenAPIRecordedSuccessResponse(t, request, recorder)
}
return recorder.Code
}
@@ -32,6 +32,9 @@ func requestRemainingVersionedRoute(t *testing.T, handler http.Handler, sessionC
// recorder 是捕获公共兼容入口响应的记录器。
recorder := httptest.NewRecorder()
handler.ServeHTTP(recorder, request)
if strings.HasPrefix(path, "/api/v1/") && recorder.Code >= http.StatusOK && recorder.Code < http.StatusMultipleChoices {
assertOpenAPIRecordedSuccessResponse(t, request, recorder)
}
return recorder.Code
}
@@ -32,6 +32,9 @@ func requestReplyRoute(t *testing.T, handler http.Handler, sessionCookie *http.C
// recorder 是捕获兼容入口响应的记录器。
recorder := httptest.NewRecorder()
handler.ServeHTTP(recorder, request)
if strings.HasPrefix(path, "/api/v1/") && recorder.Code >= http.StatusOK && recorder.Code < http.StatusMultipleChoices {
assertOpenAPIRecordedSuccessResponse(t, request, recorder)
}
return recorder.Code
}
@@ -22,9 +22,7 @@ func TestVersionedSessionRoutesPreserveLegacyContracts(t *testing.T) {
// loginRecorder 是捕获版本化登录响应的记录器。
loginRecorder := httptest.NewRecorder()
handler.ServeHTTP(loginRecorder, loginReq)
if loginRecorder.Code != http.StatusOK {
t.Fatalf("versioned login status=%d body=%s", loginRecorder.Code, loginRecorder.Body.String())
}
assertOpenAPISuccessResponse(t, loginReq, loginRecorder)
// loginResponseValue 是版本化登录响应 DTO。
var loginResponseValue loginResponse
// loginDecodeErr 是版本化登录响应反序列化失败的原因。
@@ -43,9 +41,7 @@ func TestVersionedSessionRoutesPreserveLegacyContracts(t *testing.T) {
// verifyRecorder 是捕获版本化会话校验响应的记录器。
verifyRecorder := httptest.NewRecorder()
handler.ServeHTTP(verifyRecorder, verifyReq)
if verifyRecorder.Code != http.StatusOK {
t.Fatalf("versioned verify status=%d body=%s", verifyRecorder.Code, verifyRecorder.Body.String())
}
assertOpenAPISuccessResponse(t, verifyReq, verifyRecorder)
// verifyResponseValue 是版本化会话校验响应 DTO。
var verifyResponseValue sessionVerificationResponse
// verifyDecodeErr 是版本化会话校验响应反序列化失败的原因。
@@ -72,9 +68,7 @@ func TestVersionedSessionRoutesPreserveLegacyContracts(t *testing.T) {
// logoutRecorder 是捕获版本化注销响应的记录器。
logoutRecorder := httptest.NewRecorder()
handler.ServeHTTP(logoutRecorder, logoutReq)
if logoutRecorder.Code != http.StatusOK {
t.Fatalf("versioned logout status=%d body=%s", logoutRecorder.Code, logoutRecorder.Body.String())
}
assertOpenAPISuccessResponse(t, logoutReq, logoutRecorder)
// legacyLoginReq 是验证旧登录入口仍可用的请求。
legacyLoginReq := httptest.NewRequest(http.MethodPost, "/login", strings.NewReader(loginBody))
@@ -32,6 +32,9 @@ func requestSettingsCardNotificationRoute(t *testing.T, handler http.Handler, se
// recorder 是捕获兼容入口响应的记录器。
recorder := httptest.NewRecorder()
handler.ServeHTTP(recorder, request)
if strings.HasPrefix(path, "/api/v1/") && recorder.Code >= http.StatusOK && recorder.Code < http.StatusMultipleChoices {
assertOpenAPIRecordedSuccessResponse(t, request, recorder)
}
return recorder.Code
}