Files
Ydisks-Xianyu-Helper/internal/server/automation_extra_test.go
T
Christ 16d63dc7c9 完善系统可靠性、登录风控与跨数据库回归
可靠性与数据一致性:为 SQLite、MySQL、PostgreSQL 增加 00017 至 00021 迁移,引入账号暂停时间、默认回复和批量铺货租约、自动化运行恢复、延迟任务、动作检查点与通知 outbox。补强订单、卡密发货、Cookie、批量铺货和自动化任务的原子认领、幂等更新、并发控制、失败分类、重试与进程重启恢复,并扩展跨方言覆盖。

登录与风控恢复:完善扫码、密码登录、Cookie 续期、MTOP token、UA 与 WebSocket 生命周期;加入账号级持久化浏览器目录、Playwright 主引擎和直接 Chromium/CDP 备用引擎、严格的新 x5sec 成功判定、失败控件恢复及真实浏览器集成测试。增加可配置远程滑块服务,在明确失败、链接过期和服务不可用场景中保持既定的本地回退语义。

安全与配置:通过 XIANYU_DATA_KEY 为 Cookie、登录密码、设备与访问令牌、AI/SMTP 密钥及通知配置提供 AES-256-GCM 落库加密和历史明文升级。新增出站网络目标分级、防 DNS rebinding、登录限流、HTTP 客户端超时与 SMTP 目标校验;管理员配置的 AI 服务允许可信内网地址,非可信 Webhook 和远程资源继续限制为公网目标。

自动化与通知:为发货、评价赠送、邀评和回复动作增加断点、租约、延迟执行及人工继续/重试/取消入口;通知改为 outbox 驱动的可恢复投递。同步完善账号运行态、暂停状态、续期冷却、告警审计和异常查询接口。

前端体验:新增风控验证面板、方形二维码、账号运行态合并、暂停状态保护、自动化异常处置、批量铺货状态选择、订单导入结果和最新请求门禁。完善订单搜索与导入、规则编辑、批次恢复、通知与设置页面,并为请求取消、超时、陈旧响应和主要状态转换补充 Vitest 覆盖。

测试与部署:扩展三库功能编排、SQLite 一致性备份、数据卷持久化、浏览器集成镜像、前端类型检查和构建资产分包;功能测试覆盖健康检查、订单、铺货、自动化异常、账号暂停、关键词和系统设置。更新 README 中数据密钥、可信 AI 地址和测试端口说明。

验证结果:go vet ./...、go build ./cmd/server、gofmt 检查、npm run typecheck、npm test(17 个文件、95 个用例)及 npm run build 通过。go test ./... 未完全通过:internal/adapter 仍有 2 个密码续期用例失败,internal/renewal 仍有 4 个浏览器续期调度用例失败;其余 Go 包通过,失败现状随本次既有工作区一并提交。
2026-07-14 21:20:22 +08:00

381 lines
13 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
package server
import (
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"strings"
"testing"
"xianyu-go/internal/automation"
"xianyu-go/internal/db"
)
// TestAutomationRulesCRUD 自动化规则增删查 + 校验分支。
func TestAutomationRulesCRUD(t *testing.T) {
srv, store, cleanup := newTestServer(t)
defer cleanup()
ctx := context.Background()
// 准备一个卡密组用于 send_card 动作。
cardID, _ := store.Cards.Create(ctx, &db.CardFull{Name: "卡密组1", Type: "text", TextContent: "卡密ABC", Enabled: true, UserID: 1})
// 准备一个商品。
store.DB.ExecContext(ctx, `INSERT INTO item_info (cookie_id, item_id, item_title) VALUES ('acc1','it-auto','商品A')`)
h := srv.Router()
cookie := loginHelper(t, h)
// 创建规则:付款后自动发货(send_card)。
body := `{"cookie_id":"acc1","item_id":"it-auto","trigger_type":"order_paid","enabled":true,` +
`"actions":[{"action_type":"send_card","card_id":` + itoa(cardID) + `,"delivery_count":1,"delay_seconds":0}]}`
req := httptest.NewRequest(http.MethodPost, "/automation-rules", strings.NewReader(body))
req.AddCookie(cookie)
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != 200 {
t.Fatalf("create status=%d body=%s", rec.Code, rec.Body.String())
}
var cr map[string]any
json.Unmarshal(rec.Body.Bytes(), &cr)
if cr["success"] != true {
t.Fatalf("创建失败: %+v", cr)
}
ruleID := itoa(int64(cr["id"].(float64)))
// 列表。
req2 := httptest.NewRequest(http.MethodGet, "/automation-rules", nil)
req2.AddCookie(cookie)
rec2 := httptest.NewRecorder()
h.ServeHTTP(rec2, req2)
if rec2.Code != 200 {
t.Fatalf("list status=%d", rec2.Code)
}
var arr []map[string]any
json.Unmarshal(rec2.Body.Bytes(), &arr)
if len(arr) != 1 {
t.Fatalf("应1条规则,got %d", len(arr))
}
// 更新规则(改名为自定义)。
updBody := `{"cookie_id":"acc1","item_id":"it-auto","name":"自定义规则","trigger_type":"order_paid","enabled":false,` +
`"actions":[{"action_type":"send_card","card_id":` + itoa(cardID) + `,"delivery_count":2}]}`
req3 := httptest.NewRequest(http.MethodPut, "/automation-rules/"+ruleID, strings.NewReader(updBody))
req3.AddCookie(cookie)
rec3 := httptest.NewRecorder()
h.ServeHTTP(rec3, req3)
if rec3.Code != 200 {
t.Fatalf("update status=%d body=%s", rec3.Code, rec3.Body.String())
}
// 删除。
req4 := httptest.NewRequest(http.MethodDelete, "/automation-rules/"+ruleID, nil)
req4.AddCookie(cookie)
rec4 := httptest.NewRecorder()
h.ServeHTTP(rec4, req4)
if rec4.Code != 200 {
t.Fatalf("delete status=%d", rec4.Code)
}
}
// TestAutomationRuleBadTriggerType 不支持的触发类型 400。
func TestAutomationRuleBadTriggerType(t *testing.T) {
srv, _, cleanup := newTestServer(t)
defer cleanup()
h := srv.Router()
cookie := loginHelper(t, h)
body := `{"cookie_id":"acc1","trigger_type":"bogus","actions":[{"action_type":"confirm_shipment"}]}`
req := httptest.NewRequest(http.MethodPost, "/automation-rules", strings.NewReader(body))
req.AddCookie(cookie)
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusBadRequest {
t.Fatalf("不支持触发类型应 400,got %d", rec.Code)
}
}
// TestAutomationRuleBadCookie 账号不属于当前用户 400。
func TestAutomationRuleBadCookie(t *testing.T) {
srv, _, cleanup := newTestServer(t)
defer cleanup()
h := srv.Router()
cookie := loginHelper(t, h)
body := `{"cookie_id":"other-account","trigger_type":"order_paid","actions":[{"action_type":"confirm_shipment"}]}`
req := httptest.NewRequest(http.MethodPost, "/automation-rules", strings.NewReader(body))
req.AddCookie(cookie)
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusBadRequest {
t.Fatalf("无权账号应 400,got %d", rec.Code)
}
}
// TestAutomationRuleBadActionType 不支持的动作类型 400。
func TestAutomationRuleBadActionType(t *testing.T) {
srv, _, cleanup := newTestServer(t)
defer cleanup()
h := srv.Router()
cookie := loginHelper(t, h)
body := `{"cookie_id":"acc1","trigger_type":"order_paid","actions":[{"action_type":"bogus"}]}`
req := httptest.NewRequest(http.MethodPost, "/automation-rules", strings.NewReader(body))
req.AddCookie(cookie)
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusBadRequest {
t.Fatalf("不支持动作类型应 400,got %d", rec.Code)
}
}
func TestAutomationRuleRejectsAPICard(t *testing.T) {
srv, store, cleanup := newTestServer(t)
defer cleanup()
cardID, err := store.Cards.Create(context.Background(), &db.CardFull{
Name: "旧 API 卡密", Type: "api", APIConfig: `{"url":"https://example.com"}`, Enabled: true, UserID: 1,
})
if err != nil {
t.Fatal(err)
}
h := srv.Router()
cookie := loginHelper(t, h)
body := `{"cookie_id":"acc1","trigger_type":"order_paid","actions":[{"action_type":"send_card","card_id":` + itoa(cardID) + `}]}`
req := httptest.NewRequest(http.MethodPost, "/automation-rules", strings.NewReader(body))
req.AddCookie(cookie)
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusBadRequest || !strings.Contains(rec.Body.String(), "API 卡密暂不支持") {
t.Fatalf("status=%d body=%s", rec.Code, rec.Body.String())
}
}
// TestAutomationRuleSendCardMissingCardID send_card 缺 card_id 400。
func TestAutomationRuleSendCardMissingCardID(t *testing.T) {
srv, _, cleanup := newTestServer(t)
defer cleanup()
h := srv.Router()
cookie := loginHelper(t, h)
body := `{"cookie_id":"acc1","trigger_type":"order_paid","actions":[{"action_type":"send_card","card_id":0}]}`
req := httptest.NewRequest(http.MethodPost, "/automation-rules", strings.NewReader(body))
req.AddCookie(cookie)
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusBadRequest {
t.Fatalf("send_card 缺 card_id 应 400,got %d", rec.Code)
}
}
// TestAutomationRuleSendTextMissingTemplate send_text 缺文案 400。
func TestAutomationRuleSendTextMissingTemplate(t *testing.T) {
srv, _, cleanup := newTestServer(t)
defer cleanup()
h := srv.Router()
cookie := loginHelper(t, h)
body := `{"cookie_id":"acc1","trigger_type":"order_paid","actions":[{"action_type":"send_text","message_template":""}]}`
req := httptest.NewRequest(http.MethodPost, "/automation-rules", strings.NewReader(body))
req.AddCookie(cookie)
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusBadRequest {
t.Fatalf("send_text 缺文案应 400,got %d", rec.Code)
}
}
func TestAutomationIssueEndpointsAndActiveDeleteConflict(t *testing.T) {
srv, store, cleanup := newTestServer(t)
defer cleanup()
ctx := context.Background()
admin, _ := store.Users.GetByUsername(ctx, "admin")
ruleID, err := store.Automation.Create(ctx, db.AutomationRuleInput{UserID: admin.ID, CookieID: "acc1", Name: "issue",
TriggerType: automation.TriggerBuyerReviewed, Enabled: true,
Actions: []db.AutomationActionInput{{ActionType: automation.ActionSendText, MessageTemplate: "x", Enabled: true}}})
if err != nil {
t.Fatal(err)
}
runID, _, _ := store.Automation.TryStartRun(ctx, db.AutomationRun{RuleID: ruleID, CookieID: "acc1", OrderID: "o",
TriggerType: automation.TriggerBuyerReviewed, TriggerKey: "k", RawEventJSON: `{}`, LeaseExpiresAt: 1})
_, _ = store.Automation.StartRunAction(ctx, runID, 1, 0, 1)
_ = store.Automation.QuarantineRun(ctx, runID, 1, "unknown")
h := srv.Router()
cookie := loginHelper(t, h)
listReq := httptest.NewRequest(http.MethodGet, "/automation-issues", nil)
listReq.AddCookie(cookie)
listRec := httptest.NewRecorder()
h.ServeHTTP(listRec, listReq)
if listRec.Code != http.StatusOK || !strings.Contains(listRec.Body.String(), "unknown") {
t.Fatalf("list status=%d body=%s", listRec.Code, listRec.Body.String())
}
deleteReq := httptest.NewRequest(http.MethodDelete, "/automation-rules/"+itoa(ruleID), nil)
deleteReq.AddCookie(cookie)
deleteRec := httptest.NewRecorder()
h.ServeHTTP(deleteRec, deleteReq)
if deleteRec.Code != http.StatusConflict {
t.Fatalf("active delete status=%d body=%s", deleteRec.Code, deleteRec.Body.String())
}
resolveReq := httptest.NewRequest(http.MethodPost, "/automation-runs/"+itoa(runID)+"/resolve", strings.NewReader(`{"resolution":"cancel"}`))
resolveReq.AddCookie(cookie)
resolveRec := httptest.NewRecorder()
h.ServeHTTP(resolveRec, resolveReq)
if resolveRec.Code != http.StatusOK {
t.Fatalf("resolve status=%d body=%s", resolveRec.Code, resolveRec.Body.String())
}
}
// TestAutomationRuleNoActions 缺动作 400。
func TestAutomationRuleNoActions(t *testing.T) {
srv, _, cleanup := newTestServer(t)
defer cleanup()
h := srv.Router()
cookie := loginHelper(t, h)
body := `{"cookie_id":"acc1","trigger_type":"order_paid","actions":[]}`
req := httptest.NewRequest(http.MethodPost, "/automation-rules", strings.NewReader(body))
req.AddCookie(cookie)
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusBadRequest {
t.Fatalf("缺动作应 400,got %d", rec.Code)
}
}
func TestAutomationRuleRejectsIncompatibleTriggerActions(t *testing.T) {
srv, store, cleanup := newTestServer(t)
defer cleanup()
cardID, err := store.Cards.Create(context.Background(), &db.CardFull{Name: "card", Type: "text", TextContent: "x", Enabled: true, UserID: 1})
if err != nil {
t.Fatal(err)
}
h := srv.Router()
cookie := loginHelper(t, h)
tests := []string{
`{"cookie_id":"acc1","trigger_type":"order_paid","actions":[{"action_type":"send_text","message_template":"x"}]}`,
`{"cookie_id":"acc1","trigger_type":"buyer_reviewed","actions":[{"action_type":"confirm_shipment"}]}`,
`{"cookie_id":"acc1","trigger_type":"review_missing_timeout","actions":[{"action_type":"send_card","card_id":` + itoa(cardID) + `}]}`,
}
for _, body := range tests {
req := httptest.NewRequest(http.MethodPost, "/automation-rules", strings.NewReader(body))
req.AddCookie(cookie)
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusBadRequest {
t.Fatalf("body=%s status=%d response=%s", body, rec.Code, rec.Body.String())
}
}
}
// TestAutomationRuleBadJSON 非法 JSON 400。
func TestAutomationRuleBadJSON(t *testing.T) {
srv, _, cleanup := newTestServer(t)
defer cleanup()
h := srv.Router()
cookie := loginHelper(t, h)
req := httptest.NewRequest(http.MethodPost, "/automation-rules", strings.NewReader("not-json"))
req.AddCookie(cookie)
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusBadRequest {
t.Fatalf("非法 JSON 应 400,got %d", rec.Code)
}
}
// TestAutomationRuleUpdateBadID 无效 ID 400。
func TestAutomationRuleUpdateBadID(t *testing.T) {
srv, _, cleanup := newTestServer(t)
defer cleanup()
h := srv.Router()
cookie := loginHelper(t, h)
body := `{"cookie_id":"acc1","trigger_type":"order_paid","actions":[{"action_type":"confirm_shipment"}]}`
req := httptest.NewRequest(http.MethodPut, "/automation-rules/abc", strings.NewReader(body))
req.AddCookie(cookie)
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusBadRequest {
t.Fatalf("无效 ID 应 400,got %d", rec.Code)
}
}
// TestAutomationRuleDeleteBadID 无效 ID 400。
func TestAutomationRuleDeleteBadID(t *testing.T) {
srv, _, cleanup := newTestServer(t)
defer cleanup()
h := srv.Router()
cookie := loginHelper(t, h)
req := httptest.NewRequest(http.MethodDelete, "/automation-rules/abc", nil)
req.AddCookie(cookie)
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusBadRequest {
t.Fatalf("无效 ID 应 400,got %d", rec.Code)
}
}
// TestAutomationRuleDeleteNotFound 不存在规则 404。
func TestAutomationRuleDeleteNotFound(t *testing.T) {
srv, _, cleanup := newTestServer(t)
defer cleanup()
h := srv.Router()
cookie := loginHelper(t, h)
req := httptest.NewRequest(http.MethodDelete, "/automation-rules/999999", nil)
req.AddCookie(cookie)
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusNotFound {
t.Fatalf("不存在规则应 404,got %d", rec.Code)
}
}
// TestDefaultAutomationRuleName 默认规则名。
func TestDefaultAutomationRuleName(t *testing.T) {
cases := map[string]string{
automation.TriggerOrderPaid: "付款后自动发货",
automation.TriggerBuyerReviewed: "评价后发送赠品",
automation.TriggerReviewMissingTimeout: "超时未评价求评价",
"bogus": "自动化规则",
}
for trigger, want := range cases {
got := defaultAutomationRuleName(trigger, "")
if got != want {
t.Errorf("defaultAutomationRuleName(%q)=%q want %q", trigger, got, want)
}
}
if got := defaultAutomationRuleName(automation.TriggerOrderPaid, "item-x"); got != "付款后自动发货 - item-x" {
t.Errorf("带 itemID 的默认名异常: %q", got)
}
}
// TestIsJSONObject isJSONObject 表驱动。
func TestIsJSONObject(t *testing.T) {
cases := map[string]bool{
`{}`: true,
`{"a":1}`: true,
`null`: true, // null 能 unmarshal 为 map(nil),函数判定为对象
`[]`: false,
`"str"`: false,
`invalid`: false,
``: false,
}
for in, want := range cases {
if got := isJSONObject(in); got != want {
t.Errorf("isJSONObject(%q)=%v want %v", in, got, want)
}
}
}
// TestFirstNonZero firstNonZero 表驱动。
func TestFirstNonZero(t *testing.T) {
if got := firstNonZero(0, 5); got != 5 {
t.Fatalf("got %d", got)
}
if got := firstNonZero(3, 5); got != 3 {
t.Fatalf("got %d", got)
}
}