完善系统可靠性、登录风控与跨数据库回归

可靠性与数据一致性:为 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 包通过,失败现状随本次既有工作区一并提交。
This commit is contained in:
Christ committed 2026-07-14 21:20:22 +08:00
1 parent 9a5b20d189
commit 16d63dc7c9
211 files changed
+16449 -3408

No files matched your search

+424 -256
View File
File diff suppressed because it is too large. Load diff
+146 -90
View File
@@ -10,7 +10,6 @@ import (
"time"
"xianyu-go/internal/automation"
"xianyu-go/internal/db"
"xianyu-go/internal/xianyu/mtop"
xrenew "xianyu-go/internal/xianyu/renew"
)
@@ -22,16 +21,59 @@ type riskCountingMTop struct {
func (m *riskCountingMTop) RefreshTokenWithDeviceIDContext(context.Context, string, string) (*mtop.RefreshResult, error) {
m.calls++
if m.calls > 1 {
return &mtop.RefreshResult{AccessToken: "standard-token", UpdatedCookies: "unb=123; _m_h5_tk=recovered;"}, nil
}
return nil, &mtop.RiskVerificationError{Ret: []string{"FAIL_SYS_USER_VALIDATE"}, VerificationURL: "https://verify.example"}
}
type tokenRecoveredHandler struct{ recordingHandler }
func (h *tokenRecoveredHandler) OnTokenCaptchaVerification(context.Context, string, string, string) (*mtop.RefreshResult, bool) {
func (h *tokenRecoveredHandler) OnTokenCaptchaVerification(context.Context, string, string, string, string) (*mtop.RefreshResult, bool) {
return &mtop.RefreshResult{AccessToken: "recovered-token", UpdatedCookies: "unb=123; _m_h5_tk=recovered;"}, true
}
func TestRefreshTokenUsesRecoveredAccessTokenWithoutSecondRequest(t *testing.T) {
type capturingCaptchaHandler struct {
recordingHandler
cookieStr string
deviceID string
}
func (h *capturingCaptchaHandler) OnTokenCaptchaVerification(_ context.Context, _, cookieStr, _, deviceID string) (*mtop.RefreshResult, bool) {
h.cookieStr = cookieStr
h.deviceID = deviceID
return &mtop.RefreshResult{UpdatedCookies: cookieStr + "; x5sec=fresh"}, true
}
type responseCookieRiskMTop struct{ calls int }
func (m *responseCookieRiskMTop) FetchUserProfile(context.Context, string) (*mtop.UserProfileResult, error) {
return nil, nil
}
func (m *responseCookieRiskMTop) ConsignContext(context.Context, string, string) (bool, []string, string, error) {
return true, nil, "", nil
}
func (m *responseCookieRiskMTop) FetchItemsPage(context.Context, string, int, int) (*mtop.ItemListResult, error) {
return nil, nil
}
func (m *responseCookieRiskMTop) FetchAllItems(context.Context, string, int, int) (*mtop.ItemListResult, error) {
return nil, nil
}
func (m *responseCookieRiskMTop) PublishItem(context.Context, string, mtop.PublishItemRequest) (*mtop.PublishItemResult, error) {
return nil, nil
}
func (m *responseCookieRiskMTop) RefreshTokenWithDeviceIDContext(_ context.Context, cookieStr, _ string) (*mtop.RefreshResult, error) {
m.calls++
if m.calls == 1 {
updated := strings.Replace(cookieStr, "_m_h5_tk=tk_1", "_m_h5_tk=server_1", 1)
return &mtop.RefreshResult{UpdatedCookies: updated}, &mtop.RiskVerificationError{
Ret: []string{"FAIL_SYS_USER_VALIDATE"}, VerificationURL: "https://verify.example/punish",
}
}
return &mtop.RefreshResult{AccessToken: "standard-after-captcha", UpdatedCookies: cookieStr}, nil
}
func TestRefreshTokenRetriesStandardRequestAfterCaptchaRecovery(t *testing.T) {
acc, _, _, cleanup := newAccountForTest(t)
defer cleanup()
defer acc.Stop()
@@ -43,11 +85,36 @@ func TestRefreshTokenUsesRecoveredAccessTokenWithoutSecondRequest(t *testing.T)
if err != nil {
t.Fatal(err)
}
if token != "recovered-token" || !strings.Contains(cookies, "recovered") {
if token != "standard-token" || !strings.Contains(cookies, "recovered") {
t.Fatalf("token=%q cookies=%q", token, cookies)
}
if client.calls != 1 {
t.Fatalf("refresh calls=%d want 1", client.calls)
if client.calls != 2 {
t.Fatalf("refresh calls=%d want 2", client.calls)
}
}
func TestRefreshTokenPersistsResponseCookiesBeforeCaptchaRecovery(t *testing.T) {
acc, _, store, cleanup := newRunAccount(t, &responseCookieRiskMTop{})
defer cleanup()
handler := &capturingCaptchaHandler{}
acc.handler = handler
token, _, err := acc.refreshToken(context.Background())
if err != nil {
t.Fatal(err)
}
if token != "standard-after-captcha" {
t.Fatalf("token=%q", token)
}
if !strings.Contains(handler.cookieStr, "_m_h5_tk=server_1") {
t.Fatalf("captcha handler 未收到响应先下发的 Cookie: %q", handler.cookieStr)
}
if handler.deviceID != acc.deviceID {
t.Fatalf("captcha deviceID=%q want %q", handler.deviceID, acc.deviceID)
}
saved, err := store.Cookies.GetValue(context.Background(), "cid")
if err != nil || !strings.Contains(saved, "_m_h5_tk=server_1") || !strings.Contains(saved, "x5sec=fresh") {
t.Fatalf("响应/验证 Cookie 未完整持久化: saved=%q err=%v", saved, err)
}
}
@@ -179,8 +246,8 @@ func TestTryAPIRenewSuccessShortCircuitsRecovery(t *testing.T) {
if saved != "unb=123; _m_h5_tk=tk_2;" {
t.Fatalf("DB cookie 未更新: %q", saved)
}
if _, err := store.Tokens.Get(ctx, "cid"); err != db.ErrNotFound {
t.Fatalf("接口续期更新 cookie 后应清 token,got %v", err)
if tk, err := store.Tokens.Get(ctx, "cid"); err != nil || tk.AccessToken != "" || tk.DeviceID != acc.deviceID {
t.Fatalf("接口续期后应清 token 并保留 device ID: tk=%+v err=%v", tk, err)
}
}
@@ -210,8 +277,8 @@ func TestTryAPIRenewPartialCookiesContinueRecovery(t *testing.T) {
if saved != "unb=123; _m_h5_tk=partial;" {
t.Fatalf("部分 cookie 应先保存到 DB: %q", saved)
}
if _, err := store.Tokens.Get(ctx, "cid"); err != db.ErrNotFound {
t.Fatalf("部分 cookie 更新后也应清 token,got %v", err)
if tk, err := store.Tokens.Get(ctx, "cid"); err != nil || tk.AccessToken != "" || tk.DeviceID != acc.deviceID {
t.Fatalf("部分 cookie 更新后应清 token 并保留 device ID: tk=%+v err=%v", tk, err)
}
}
@@ -321,12 +388,12 @@ func TestRetryDelay_FailureClampsAtOne(t *testing.T) {
acc, _, _, cleanup := newAccountForTest(t)
defer cleanup()
acc.connFailures = 0
// close-frame:min(3*1,15)=3s。
expectDelayRange(t, acc.retryDelay("no close frame received or sent"), 3*time.Second)
// timeout:min(10*1,60)=10s。
expectDelayRange(t, acc.retryDelay("timeout reading"), 10*time.Second)
// default:min(5*1,30)=5s。
expectDelayRange(t, acc.retryDelay("random error"), 5*time.Second)
// close-frame:min(2^1,30)=2s。
expectDelayRange(t, acc.retryDelay("no close frame received or sent"), 2*time.Second)
// timeout:min(2*2^1,90)=4s。
expectDelayRange(t, acc.retryDelay("timeout reading"), 4*time.Second)
// default:min(2^1,45)=2s。
expectDelayRange(t, acc.retryDelay("random error"), 2*time.Second)
}
// TestRetryDelay_TimeoutVariant "timeout" 关键词分支。
@@ -334,15 +401,57 @@ func TestRetryDelay_TimeoutVariant(t *testing.T) {
acc, _, _, cleanup := newAccountForTest(t)
defer cleanup()
acc.connFailures = 3
// min(10*3,60)=30s。
expectDelayRange(t, acc.retryDelay("dial timeout"), 30*time.Second)
// min(2*2^3,90)=16s。
expectDelayRange(t, acc.retryDelay("dial timeout"), 16*time.Second)
acc.connFailures = 10
expectDelayRange(t, acc.retryDelay("timeout"), 60*time.Second)
expectDelayRange(t, acc.retryDelay("timeout"), 90*time.Second)
}
// TestHandleMaxFailures_RecentMessageSkipPasswordLogin 最近仍收到消息时跳过密码登录刷新,
// 重置失败计数并返回 nil(睡眠时间可被 ctx 取消)。
func TestHandleMaxFailures_RecentMessageSkipPasswordLogin(t *testing.T) {
func TestNetworkRetryDelayMatchesReferenceBackoff(t *testing.T) {
acc, _, _, cleanup := newAccountForTest(t)
defer cleanup()
acc.networkFailures = 1
expectDelayRange(t, acc.networkRetryDelay(), 4*time.Second)
acc.networkFailures = 10
expectDelayRange(t, acc.networkRetryDelay(), 60*time.Second)
}
func TestEstablishedNetworkErrorClassification(t *testing.T) {
for _, err := range []error{
errors.New("ConnectionClosedError"), errors.New("no close frame received or sent"),
errors.New("WS read: connection reset by peer"), errors.New("received close frame"),
} {
if !isEstablishedNetworkError(err) {
t.Fatalf("应识别为已建立连接后的网络错误: %v", err)
}
}
if isEstablishedNetworkError(errors.New("device id or appkey is not equal")) {
t.Fatal("注册认证错误不应归类为纯网络断线")
}
}
func TestRecordShortDisconnectDisablesAtFiveWithinWindow(t *testing.T) {
acc, _, _, cleanup := newAccountForTest(t)
defer cleanup()
for i := 1; i < FrequentDisconnectLimit; i++ {
if acc.recordShortDisconnect(time.Second) {
t.Fatalf("第 %d 次短连接不应达到阈值", i)
}
}
if !acc.recordShortDisconnect(time.Second) {
t.Fatal("5 分钟内第 5 次短连接应达到禁用阈值")
}
if acc.recordShortDisconnect(ShortConnectionThreshold) {
t.Fatal("长连接应清空短连接记录")
}
if len(acc.shortDisconnects) != 0 {
t.Fatalf("长连接后短连接记录未清空: %d", len(acc.shortDisconnects))
}
}
// TestHandleMaxFailures_RecentMessageStillRunsRecovery 消息冷却只约束 Token/Cookie
// 刷新,不约束达到认证失败阈值后的恢复链。
func TestHandleMaxFailures_RecentMessageStillRunsRecovery(t *testing.T) {
acc, h, _, cleanup := newAccountForTest(t)
defer cleanup()
ctx := context.Background()
@@ -353,43 +462,14 @@ func TestHandleMaxFailures_RecentMessageSkipPasswordLogin(t *testing.T) {
acc.connFailures = MaxConnectionFailures
acc.mu.Unlock()
// 最近消息路径会 resetFailures 后进入 sleepCtx 等待 retryDelay。
// 用一个短超时 ctx 让 sleepCtx 提前返回 ctx.Err(),证明走了 sleep 分支(而非密码刷新)。
cctx, cancel := context.WithTimeout(ctx, 30*time.Millisecond)
defer cancel()
err := acc.handleMaxFailures(cctx)
if err != cctx.Err() {
t.Fatalf("最近收到消息应走 sleep 分支返回 ctx.Err(),got %v want %v", err, cctx.Err())
t.Fatalf("成功恢复后的等待应响应 ctx 取消,got %v want %v", err, cctx.Err())
}
if h.refresh != 0 {
t.Errorf("不应触发密码登录刷新,got %d", h.refresh)
}
if acc.connFailures != 0 {
t.Errorf("应重置失败计数,got %d", acc.connFailures)
}
}
// TestHandleMaxFailures_PasswordLoginCooldown 密码登录刷新冷却中跳过本次刷新。
func TestHandleMaxFailures_PasswordLoginCooldown(t *testing.T) {
acc, h, _, cleanup := newAccountForTest(t)
defer cleanup()
ctx := context.Background()
// 无最近消息,但最近做过密码登录(在 PasswordLoginMinGap 内)。
acc.mu.Lock()
acc.lastMsgReceived = time.Time{} // 零值,绕过 message cooldown
acc.lastPasswordLogin = time.Now()
acc.connFailures = MaxConnectionFailures
acc.mu.Unlock()
cctx, cancel := context.WithTimeout(ctx, 30*time.Millisecond)
defer cancel()
err := acc.handleMaxFailures(cctx)
if err != cctx.Err() {
t.Fatalf("冷却中应走 sleep 分支返回 ctx.Err(),got %v want %v", err, cctx.Err())
}
if h.refresh != 0 {
t.Errorf("冷却中不应调用 OnPasswordLoginRefresh,got %d", h.refresh)
if h.refresh != 1 {
t.Errorf("应触发一次恢复链,got %d", h.refresh)
}
if acc.connFailures != 0 {
t.Errorf("应重置失败计数,got %d", acc.connFailures)
@@ -405,7 +485,6 @@ func TestHandleMaxFailures_PasswordLoginSuccess(t *testing.T) {
// 无最近消息、未在密码登录冷却中。
acc.mu.Lock()
acc.lastMsgReceived = time.Time{}
acc.lastPasswordLogin = time.Time{}
acc.connFailures = MaxConnectionFailures
acc.mu.Unlock()
@@ -467,15 +546,13 @@ func (f *failingRefreshHandler) OnAccountEvent(_ context.Context, _, eventType,
f.alerts = append(f.alerts, level)
}
// TestHandleMaxFailures_PasswordLoginFailure 密码登录刷新失败:不再硬退出,进入慢重试,
// 状态 AuthExpired,触发一次 critical 告警。
// TestHandleMaxFailures_PasswordLoginFailure 密码登录刷新失败后终止账号主循环。
func TestHandleMaxFailures_PasswordLoginFailure(t *testing.T) {
acc, _, _, cleanup := newAccountForTest(t)
defer cleanup()
acc.mu.Lock()
acc.lastMsgReceived = time.Time{}
acc.lastPasswordLogin = time.Time{}
acc.connFailures = MaxConnectionFailures
acc.mu.Unlock()
@@ -483,13 +560,9 @@ func TestHandleMaxFailures_PasswordLoginFailure(t *testing.T) {
h := &failingRefreshHandler{}
acc.handler = h
// 新行为:不再 return fatal error,而是 sleepCtx(AuthExpiredRetryInterval) 慢重试。
// 用短超时 ctx 让 sleepCtx 提前返回 ctx.Err(),证明走了慢重试分支而非硬退出。
cctx, cancel := context.WithTimeout(context.Background(), 30*time.Millisecond)
defer cancel()
err := acc.handleMaxFailures(cctx)
if err != cctx.Err() {
t.Fatalf("刷新失败应走慢重试 sleep 分支返回 ctx.Err(),got %v want %v", err, cctx.Err())
err := acc.handleMaxFailures(context.Background())
if err == nil || !strings.Contains(err.Error(), "自动恢复失败") {
t.Fatalf("刷新失败应返回终止主循环的错误,got %v", err)
}
if s := acc.RuntimeStatus(); s.State != RuntimeAuthExpired {
t.Errorf("状态应为 auth_expired,got %q", s.State)
@@ -502,7 +575,7 @@ func TestHandleMaxFailures_PasswordLoginFailure(t *testing.T) {
}
}
// TestReplaceCookieStr_UpdateUserIDAndDeviceID 更新 cookie 后 unb 变化时重置 deviceID。
// TestReplaceCookieStr_UpdateUserIDAndDeviceID 更新 cookie 不得改变永久 deviceID。
func TestReplaceCookieStr_UpdateUserIDAndDeviceID(t *testing.T) {
acc, _, _, cleanup := newAccountForTest(t)
defer cleanup()
@@ -532,17 +605,17 @@ func TestReplaceCookieStr_UpdateUserIDAndDeviceID(t *testing.T) {
if newDevice == "" {
t.Error("deviceID 不应为空")
}
// 不同 unb 应重新生成 deviceID(基于 unb 的哈希)。
if newDevice == oldDevice {
t.Error("unb 变化后 deviceID 应重新生成")
if newDevice != oldDevice {
t.Error("unb 变化后 deviceID 仍应保持不变")
}
if newCookie != "unb=456; _m_h5_tk=tk2;" {
t.Errorf("CookieStr 未更新: got %q", newCookie)
}
}
// TestReplaceCookieStr_EmptyDeviceIDFallback deviceID 为空且 cookie 含 unb 时兜底生成。
func TestReplaceCookieStr_EmptyDeviceIDFallback(t *testing.T) {
// TestReplaceCookieStrDoesNotGenerateDeviceID ensures cookie mutation cannot
// silently replace the identity established during account construction.
func TestReplaceCookieStrDoesNotGenerateDeviceID(t *testing.T) {
acc, _, _, cleanup := newAccountForTest(t)
defer cleanup()
// 清空 deviceID 与 UserID,模拟异常状态。
@@ -559,8 +632,8 @@ func TestReplaceCookieStr_EmptyDeviceIDFallback(t *testing.T) {
if u != "789" {
t.Errorf("UserID=%q want 789", u)
}
if d == "" {
t.Error("deviceID 应兜底生成")
if d != "" {
t.Error("Cookie 更新不应隐式生成 deviceID")
}
}
@@ -624,23 +697,6 @@ func TestCurrentCookieStr(t *testing.T) {
}
}
// TestMinDuration 取较小值。
func TestMinDuration(t *testing.T) {
cases := []struct {
a, b, want time.Duration
}{
{1 * time.Second, 2 * time.Second, 1 * time.Second},
{2 * time.Second, 1 * time.Second, 1 * time.Second},
{5 * time.Second, 5 * time.Second, 5 * time.Second},
{0, 3 * time.Second, 0},
}
for _, c := range cases {
if got := minDuration(c.a, c.b); got != c.want {
t.Errorf("minDuration(%v,%v)=%v want %v", c.a, c.b, got, c.want)
}
}
}
// TestSleepCtx 正常睡眠返回 nil;ctx 取消返回 ctx.Err();d<=0 立即返回。
func TestSleepCtx(t *testing.T) {
// d<=0 立即返回 nil。
+14 -1
View File
@@ -8,13 +8,16 @@ import (
"fmt"
"log/slog"
"math"
"net/http"
"regexp"
"strconv"
"strings"
"time"
"github.com/sashabaranov/go-openai"
"xianyu-go/internal/db"
"xianyu-go/internal/netguard"
)
const (
@@ -22,6 +25,10 @@ const (
defaultAIModel = "qwen-plus"
)
var newAIHTTPClient = func(baseURL string) (*http.Client, error) {
return netguard.TrustedEndpointHTTPClient(baseURL, 30*time.Second)
}
// AIReplierImpl AI 回复实现。
type AIReplierImpl struct {
cookieID string
@@ -79,6 +86,10 @@ func (a *AIReplierImpl) Reply(ctx context.Context, m ChatMessage) (*ReplyResult,
if aiCfg.BaseURL != "" {
clientCfg.BaseURL = aiCfg.BaseURL
}
clientCfg.HTTPClient, err = newAIHTTPClient(clientCfg.BaseURL)
if err != nil {
return nil, fmt.Errorf("AI API 地址无效: %w", err)
}
client := openai.NewClientWithConfig(clientCfg)
messages := []openai.ChatCompletionMessage{{Role: openai.ChatMessageRoleSystem, Content: systemPrompt}}
@@ -91,7 +102,9 @@ func (a *AIReplierImpl) Reply(ctx context.Context, m ChatMessage) (*ReplyResult,
}
messages = append(messages, openai.ChatCompletionMessage{Role: openai.ChatMessageRoleUser, Content: m.Text})
resp, err := client.CreateChatCompletion(ctx, openai.ChatCompletionRequest{
aiCtx, cancel := context.WithTimeout(ctx, 30*time.Second)
defer cancel()
resp, err := client.CreateChatCompletion(aiCtx, openai.ChatCompletionRequest{
Model: aiCfg.Model,
Messages: messages,
Temperature: 0.7,
+23 -1
View File
@@ -21,7 +21,24 @@ func (a *Account) dispatch(decrypted map[string]any) {
a.lastMsgReceived = time.Now()
a.mu.Unlock()
// 信号量限并发(非阻塞获取,超限则丢弃并告警——避免阻塞 WS 读取)。
// 系统业务事件不能丢弃:并发满时让 WS 读取产生背压,等待处理槽位。
// 普通聊天仍采用非阻塞限流,避免聊天洪峰拖垮连接。
isSystemEvent := automation.ExtractTaskFromWS(a.CookieID, a.currentCookieStr(), decrypted) != nil
if isSystemEvent {
select {
case a.sem <- struct{}{}:
case <-ctx.Done():
a.taskWG.Done()
return
}
go func() {
defer a.taskWG.Done()
defer func() { <-a.sem }()
a.handleMessageContext(ctx, decrypted)
}()
return
}
select {
case a.sem <- struct{}{}:
default:
@@ -305,6 +322,11 @@ func (a *Account) currentCookieStr() string {
return a.CookieStr
}
// CurrentCookieStr 线程安全地返回账号当前使用的 Cookie。
func (a *Account) CurrentCookieStr() string {
return a.currentCookieStr()
}
// ---- 小工具 ----
func contains(s, sub string) bool { return strings.Contains(strings.ToLower(s), strings.ToLower(sub)) }
+47
View File
@@ -210,6 +210,53 @@ func TestDispatch_SemaphoreOverflowDrops(t *testing.T) {
}
}
func TestDispatch_SystemEventWaitsForCapacityInsteadOfDropping(t *testing.T) {
acc, _, _, cleanup := newAccountForTest(t)
defer cleanup()
defer acc.Stop()
h := &systemCapturingHandler{}
acc.handler = h
for i := 0; i < MessageSemaphoreSize; i++ {
acc.sem <- struct{}{}
}
event := mustPaidDeliveryCard(t)
done := make(chan struct{})
go func() {
acc.dispatch(event)
close(done)
}()
select {
case <-done:
t.Fatal("system event was dropped while semaphore was full")
case <-time.After(100 * time.Millisecond):
}
<-acc.sem
select {
case <-done:
case <-time.After(time.Second):
t.Fatal("system event did not continue after capacity became available")
}
deadline := time.Now().Add(time.Second)
for time.Now().Before(deadline) {
h.mu.Lock()
count := len(h.tasks)
h.mu.Unlock()
if count == 1 {
break
}
time.Sleep(10 * time.Millisecond)
}
h.mu.Lock()
count := len(h.tasks)
h.mu.Unlock()
if count != 1 {
t.Fatalf("system event count=%d want 1", count)
}
for len(acc.sem) > 0 {
<-acc.sem
}
}
// TestScheduleDebouncedReply_DifferentChatIDsNotCoalesced 不同 chat_id 的消息各自独立防抖,不合并。
func TestScheduleDebouncedReply_DifferentChatIDsNotCoalesced(t *testing.T) {
acc, h, _, cleanup := newAccountForTest(t)
+6 -6
View File
@@ -281,20 +281,20 @@ func TestRetryDelay(t *testing.T) {
defer acc.Stop()
acc.connFailures = 1
expectDelayRange(t, acc.retryDelay("no close frame received or sent"), 3*time.Second)
expectDelayRange(t, acc.retryDelay("no close frame received or sent"), 2*time.Second)
acc.connFailures = 10
expectDelayRange(t, acc.retryDelay("no close frame received or sent"), 15*time.Second)
expectDelayRange(t, acc.retryDelay("no close frame received or sent"), 30*time.Second)
acc.connFailures = 2
expectDelayRange(t, acc.retryDelay("connection refused"), 20*time.Second)
expectDelayRange(t, acc.retryDelay("connection refused"), 8*time.Second)
acc.connFailures = 10
expectDelayRange(t, acc.retryDelay("connection refused"), 60*time.Second)
expectDelayRange(t, acc.retryDelay("connection refused"), 90*time.Second)
acc.connFailures = 1
expectDelayRange(t, acc.retryDelay("some other error"), 5*time.Second)
expectDelayRange(t, acc.retryDelay("some other error"), 2*time.Second)
}
func expectDelayRange(t *testing.T, got, base time.Duration) {
t.Helper()
max := base + base/3
max := base + base*3/10
if got < base || got > max {
t.Fatalf("retryDelay=%v want in [%v,%v]", got, base, max)
}
+13
View File
@@ -0,0 +1,13 @@
package engine
import (
"net/http"
"time"
)
func init() {
// AI 单测通过 httptest 模拟兼容端点;生产构造器仍使用 netguard。
newAIHTTPClient = func(string) (*http.Client, error) {
return &http.Client{Timeout: 30 * time.Second}, nil
}
}
+286 -42
View File
@@ -2,6 +2,8 @@ package engine
import (
"context"
"errors"
"strings"
"sync/atomic"
"testing"
"time"
@@ -26,6 +28,258 @@ type statusMtop struct {
err error
}
type failingCountingMtop struct {
fakeRunMtop
calls int32
err error
}
func (c *failingCountingMtop) RefreshTokenWithDeviceIDContext(_ context.Context, _ string, _ string) (*mtop.RefreshResult, error) {
atomic.AddInt32(&c.calls, 1)
return nil, c.err
}
func TestRiskSensitiveRefreshIntervals(t *testing.T) {
if CookieRefreshInterval != 180*time.Second {
t.Fatalf("在线 Cookie 检查间隔应与参考实现保持 180 秒,got %s", CookieRefreshInterval)
}
if CookieRefreshCheckInterval != time.Minute {
t.Fatalf("在线 Cookie 循环检查频率应与参考实现保持 60 秒,got %s", CookieRefreshCheckInterval)
}
if PasswordLoginMinGap != 60*time.Second {
t.Fatalf("自动密码登录冷却应与参考运行时保持 60 秒,got %s", PasswordLoginMinGap)
}
}
func TestRefreshOnlineCookie_CacheHitSkipsMtop(t *testing.T) {
mtopClient := &countingMtop{fakeRunMtop: fakeRunMtop{token: "tok-mtop"}}
acc, _, store, cleanup := newRunAccount(t, mtopClient)
defer cleanup()
if err := store.Tokens.Save(context.Background(), "cid", acc.deviceID, "cached-tok",
time.Now().Add(time.Hour).Unix()); err != nil {
t.Fatal(err)
}
conn := &fakeWSConn{}
if !acc.refreshOnlineCookie(context.Background(), conn, true) {
t.Fatal("缓存命中时在线 Cookie 检查应成功")
}
if calls := atomic.LoadInt32(&mtopClient.calls); calls != 0 {
t.Fatalf("180 秒检查命中缓存时不应请求 mtop,got %d", calls)
}
acc.mu.Lock()
currentToken := acc.currentToken
lastRefresh := acc.lastCookieRefresh
acc.mu.Unlock()
if currentToken != "cached-tok" || lastRefresh.IsZero() {
t.Fatalf("应采用缓存 token 并更新时间,token=%q last_refresh=%s", currentToken, lastRefresh)
}
}
func TestCookieRefreshLoopRunsInitialCacheCheckImmediately(t *testing.T) {
mtopClient := &countingMtop{fakeRunMtop: fakeRunMtop{token: "tok-mtop"}}
acc, _, store, cleanup := newRunAccount(t, mtopClient)
defer cleanup()
if err := store.Tokens.Save(context.Background(), "cid", acc.deviceID, "cached-tok",
time.Now().Add(time.Hour).Unix()); err != nil {
t.Fatal(err)
}
acc.mu.Lock()
acc.lastCookieRefresh = time.Time{}
acc.lastMsgReceived = time.Now().Add(-MessageCooldown - time.Second)
acc.mu.Unlock()
ctx, cancel := context.WithCancel(context.Background())
done := make(chan struct{})
go func() {
defer close(done)
acc.cookieRefreshLoop(ctx, nil)
}()
deadline := time.Now().Add(time.Second)
for time.Now().Before(deadline) {
acc.mu.Lock()
lastRefresh := acc.lastCookieRefresh
lastMessage := acc.lastMsgReceived
acc.mu.Unlock()
if !lastRefresh.IsZero() {
if !lastMessage.IsZero() {
t.Fatalf("刷新轮次结束后应清空消息冷却标识: %s", lastMessage)
}
break
}
time.Sleep(5 * time.Millisecond)
}
cancel()
<-done
acc.mu.Lock()
lastRefresh := acc.lastCookieRefresh
acc.mu.Unlock()
if lastRefresh.IsZero() {
t.Fatal("Cookie 刷新循环启动后应立即完成首次缓存检查")
}
if calls := atomic.LoadInt32(&mtopClient.calls); calls != 0 {
t.Fatalf("首次检查命中缓存时不应请求 mtop, got %d", calls)
}
}
func TestRefreshOnlineCookie_RiskRecoveryRestoresOnlineRuntimeState(t *testing.T) {
mtopClient := &riskCountingMTop{}
acc, _, _, cleanup := newRunAccount(t, mtopClient)
defer cleanup()
acc.handler = &tokenRecoveredHandler{}
conn := &fakeWSConn{}
acc.mu.Lock()
acc.conn = conn
acc.runtimeState = RuntimeOnline
acc.runtimeMessage = "消息服务连接正常"
acc.runtimeUpdatedAt = time.Now()
acc.mu.Unlock()
if !acc.refreshOnlineCookie(context.Background(), conn, true) {
t.Fatal("风控自动恢复成功后在线 Cookie 刷新应成功")
}
status := acc.RuntimeStatus()
if status.State != RuntimeOnline || !status.Connected || status.Message != "消息服务连接正常" {
t.Fatalf("在线风控恢复后运行态未收敛: %+v", status)
}
conn.mu.Lock()
defer conn.mu.Unlock()
if len(conn.tokens) != 1 || conn.tokens[0] != "standard-token" {
t.Fatalf("恢复 token 未更新到现有连接: %+v", conn.tokens)
}
}
func TestApplyOnlineToken_PeriodicRefreshRestoresRuntimeWithoutChangingCookieSchedule(t *testing.T) {
acc, _, _, cleanup := newRunAccount(t, &fakeRunMtop{token: "unused"})
defer cleanup()
conn := &fakeWSConn{}
acc.mu.Lock()
acc.conn = conn
acc.runtimeState = RuntimeConnecting
acc.runtimeMessage = tokenRiskRecoveryMessage
acc.lastCookieRefresh = time.Time{}
acc.mu.Unlock()
acc.applyOnlineToken(conn, "periodic-token", false)
status := acc.RuntimeStatus()
if status.State != RuntimeOnline || !status.Connected || status.Message != "消息服务连接正常" {
t.Fatalf("定时 token 风控恢复后运行态未收敛: %+v", status)
}
acc.mu.Lock()
lastCookieRefresh := acc.lastCookieRefresh
acc.mu.Unlock()
if !lastCookieRefresh.IsZero() {
t.Fatalf("定时 token 刷新不应改变 180 秒 Cookie 检查时间: %s", lastCookieRefresh)
}
conn.mu.Lock()
defer conn.mu.Unlock()
if len(conn.tokens) != 1 || conn.tokens[0] != "periodic-token" {
t.Fatalf("定时刷新 token 未更新到现有连接: %+v", conn.tokens)
}
}
func TestRunOnlineCookieRefresh_RetriesOnceAndPacesFailure(t *testing.T) {
mtopClient := &failingCountingMtop{
fakeRunMtop: fakeRunMtop{token: "unused"},
err: errors.New("temporary token failure"),
}
acc, _, _, cleanup := newRunAccount(t, mtopClient)
defer cleanup()
started := time.Now()
if !acc.runOnlineCookieRefresh(context.Background(), &fakeWSConn{}, 0) {
t.Fatal("未取消的刷新轮次不应要求退出")
}
if calls := atomic.LoadInt32(&mtopClient.calls); calls != 2 {
t.Fatalf("失败后应且只应重试一次,got %d calls", calls)
}
if elapsed := time.Since(started); elapsed >= time.Second {
t.Fatalf("参考实现没有额外一分钟防抖,零延迟测试不应阻塞,elapsed=%s", elapsed)
}
acc.mu.Lock()
lastRefresh := acc.lastCookieRefresh
acc.mu.Unlock()
if lastRefresh.Before(started) {
t.Fatalf("第二次失败后必须重新开始 180 秒计时,last_refresh=%s started=%s", lastRefresh, started)
}
}
func TestRefreshTokenNetworkFailureClearsMemoryButPreservesFreshCache(t *testing.T) {
mtopClient := &failingCountingMtop{
fakeRunMtop: fakeRunMtop{token: "unused"},
err: errors.New("network connection reset"),
}
acc, _, store, cleanup := newRunAccount(t, mtopClient)
defer cleanup()
if err := store.Tokens.Save(context.Background(), "cid", acc.deviceID, "cached-tok",
time.Now().Add(time.Hour).Unix()); err != nil {
t.Fatal(err)
}
acc.mu.Lock()
acc.currentToken = "old-memory-token"
acc.mu.Unlock()
if _, _, err := acc.refreshToken(context.Background()); err == nil {
t.Fatal("网络失败应返回错误")
}
acc.mu.Lock()
current := acc.currentToken
acc.mu.Unlock()
if current != "" {
t.Fatalf("刷新网络失败后应清空内存 token: %q", current)
}
if cached, err := store.Tokens.Get(context.Background(), "cid"); err != nil || cached.AccessToken != "cached-tok" {
t.Fatalf("网络失败应保留未过期数据库缓存: cached=%+v err=%v", cached, err)
}
}
func TestRefreshTokenBusinessFailureClearsMemoryAndCache(t *testing.T) {
mtopClient := &failingCountingMtop{
fakeRunMtop: fakeRunMtop{token: "unused"},
err: errors.New("token API business rejected"),
}
acc, _, store, cleanup := newRunAccount(t, mtopClient)
defer cleanup()
if err := store.Tokens.Save(context.Background(), "cid", acc.deviceID, "cached-tok",
time.Now().Add(time.Hour).Unix()); err != nil {
t.Fatal(err)
}
acc.mu.Lock()
acc.currentToken = "old-memory-token"
acc.mu.Unlock()
if _, _, err := acc.refreshToken(context.Background()); err == nil {
t.Fatal("业务失败应返回错误")
}
acc.mu.Lock()
current := acc.currentToken
acc.mu.Unlock()
if current != "" {
t.Fatalf("业务失败后应清空内存 token: %q", current)
}
if tk, err := store.Tokens.Get(context.Background(), "cid"); err != nil || tk.AccessToken != "" || tk.DeviceID != acc.deviceID {
t.Fatalf("业务失败应清 token 并保留 device ID: tk=%+v err=%v", tk, err)
}
}
func TestAcquireTokenDeletesExpiredCacheBeforeNetworkAttempt(t *testing.T) {
mtopClient := &failingCountingMtop{
fakeRunMtop: fakeRunMtop{token: "unused"},
err: errors.New("network connection reset"),
}
acc, _, store, cleanup := newRunAccount(t, mtopClient)
defer cleanup()
if err := store.Tokens.Save(context.Background(), "cid", acc.deviceID, "expired-tok",
time.Now().Add(-time.Minute).Unix()); err != nil {
t.Fatal(err)
}
if _, _, err := acc.acquireToken(context.Background()); err == nil {
t.Fatal("后续网络请求失败应返回错误")
}
if tk, err := store.Tokens.Get(context.Background(), "cid"); err != nil || tk.AccessToken != "" || tk.DeviceID != acc.deviceID {
t.Fatalf("过期 token 应清空且 device ID 保留: tk=%+v err=%v", tk, err)
}
}
func (s *statusMtop) CheckLoginStatusContext(context.Context, string) (*mtop.LoginStatusResult, error) {
return s.result, s.err
}
@@ -40,7 +294,10 @@ func TestAcquireToken_CacheHitSkipsMtop(t *testing.T) {
time.Now().Add(time.Hour).Unix()); err != nil {
t.Fatal(err)
}
token, _, err := acc.acquireToken(context.Background())
if err := store.Cookies.UpdateValueExisting(context.Background(), "cid", "unb=123; _m_h5_tk=db-new;"); err != nil {
t.Fatal(err)
}
token, cookies, err := acc.acquireToken(context.Background())
if err != nil {
t.Fatalf("acquireToken: %v", err)
}
@@ -50,6 +307,25 @@ func TestAcquireToken_CacheHitSkipsMtop(t *testing.T) {
if calls := atomic.LoadInt32(&mtopClient.calls); calls != 0 {
t.Fatalf("缓存命中不应调用 mtop,got %d", calls)
}
if strings.Contains(cookies, "db-new") {
t.Fatalf("缓存命中时不应提前重载 DB Cookie: %q", cookies)
}
}
func TestAcquireRuntimeTokenPreservesMemoryTokenWithoutDatabaseCache(t *testing.T) {
mtopClient := &countingMtop{fakeRunMtop: fakeRunMtop{token: "tok-mtop"}}
acc, _, store, cleanup := newRunAccount(t, mtopClient)
defer cleanup()
acc.currentToken = "runtime-token"
_ = store.Tokens.Clear(context.Background(), "cid")
token, _, err := acc.acquireRuntimeToken(context.Background())
if err != nil || token != "runtime-token" {
t.Fatalf("runtime token=%q err=%v", token, err)
}
if calls := atomic.LoadInt32(&mtopClient.calls); calls != 0 {
t.Fatalf("网络重连复用内存 token 时不应调用 mtop,calls=%d", calls)
}
}
// TestAcquireToken_CacheMissCallsMtopAndSavesCache 缓存未命中时调 mtop 并把结果落库。
@@ -109,8 +385,8 @@ func TestTryLoginStatusCheck_AdoptsUpdatedCookie(t *testing.T) {
if err != nil || saved != newCookie {
t.Fatalf("DB Cookie 未更新: got %q err=%v", saved, err)
}
if _, err := store.Tokens.Get(context.Background(), "cid"); err == nil {
t.Fatal("Cookie 更新后应清除旧 token")
if tk, err := store.Tokens.Get(context.Background(), "cid"); err != nil || tk.AccessToken != "" || tk.DeviceID != acc.deviceID {
t.Fatalf("Cookie 更新后应清 token 并保留 device ID: tk=%+v err=%v", tk, err)
}
}
@@ -155,60 +431,28 @@ func TestReloadCookieFromDB_AdoptsNewCookieAndClearsCache(t *testing.T) {
t.Fatalf("Save: %v", err)
}
acc.reloadCookieFromDB(context.Background())
if acc.CookieStr != newCookie {
t.Fatalf("应采纳 DB 新 cookie,got %s", acc.CookieStr)
if got := acc.CurrentCookieStr(); got != newCookie {
t.Fatalf("应采纳 DB 新 cookie,got %s", got)
}
// 新 cookie 对应新 session,旧 token 缓存应被清除。
if _, err := store.Tokens.Get(context.Background(), "cid"); err == nil {
t.Fatal("cookie 变更后应清除 token 缓存")
// 新 cookie 对应新 session,旧 token 应清除但 device ID 必须保留。
if tk, err := store.Tokens.Get(context.Background(), "cid"); err != nil || tk.AccessToken != "" || tk.DeviceID != acc.deviceID {
t.Fatalf("cookie 变更后应清 token 并保留 device ID: tk=%+v err=%v", tk, err)
}
}
// TestClearCacheIfShortConnection 短连接清缓存、长连接与零值不清。
func TestClearCacheIfShortConnection(t *testing.T) {
acc, _, store, cleanup := newRunAccount(t, &fakeRunMtop{token: "tok-1"})
defer cleanup()
// 短连接(1s 前 startedAt)→ 清缓存。
store.Tokens.Save(context.Background(), "cid", acc.deviceID, "cached",
time.Now().Add(time.Hour).Unix())
acc.clearCacheIfShortConnection(context.Background(), time.Now().Add(-1*time.Second))
if _, err := store.Tokens.Get(context.Background(), "cid"); err == nil {
t.Fatal("短连接应清除 token 缓存")
}
// 长连接(2min 前)→ 不清缓存。
store.Tokens.Save(context.Background(), "cid", acc.deviceID, "cached2",
time.Now().Add(time.Hour).Unix())
acc.clearCacheIfShortConnection(context.Background(), time.Now().Add(-2*time.Minute))
if tk, err := store.Tokens.Get(context.Background(), "cid"); err != nil || tk.AccessToken != "cached2" {
t.Fatalf("长连接不应清缓存,got tk=%+v err=%v", tk, err)
}
// 零值 startedAt → 不清缓存。
acc.clearCacheIfShortConnection(context.Background(), time.Time{})
if tk, err := store.Tokens.Get(context.Background(), "cid"); err != nil || tk.AccessToken != "cached2" {
t.Fatalf("零值 startedAt 不应清缓存,got tk=%+v err=%v", tk, err)
}
}
// TestHandleMaxFailures_AlertOnce 连续两次进入 false 慢重试路径只告警一次。
// TestHandleMaxFailures_AlertOnce 连续两次进入 false 终止路径只告警一次。
func TestHandleMaxFailures_AlertOnce(t *testing.T) {
acc, _, _, cleanup := newAccountForTest(t)
defer cleanup()
h := &failingRefreshHandler{}
acc.handler = h
// 两次都进入 false 路径:每次复位密码登录冷却,让第二次也走到 markAuthExpired。
call := func() {
acc.mu.Lock()
acc.lastMsgReceived = time.Time{}
acc.lastPasswordLogin = time.Time{}
acc.connFailures = MaxConnectionFailures
acc.mu.Unlock()
cctx, cancel := context.WithTimeout(context.Background(), 30*time.Millisecond)
defer cancel()
_ = acc.handleMaxFailures(cctx)
_ = acc.handleMaxFailures(context.Background())
}
call()
call()
+58 -22
View File
@@ -2,9 +2,11 @@ package engine
import (
"context"
"errors"
"log/slog"
"path/filepath"
"sync"
"sync/atomic"
"testing"
"time"
@@ -68,6 +70,7 @@ type fakeWSConn struct {
onReceive func(onMessage func(map[string]any))
// recvBlock 控制 ReceiveLoop 是否阻塞到 ctx 取消(默认 true)。
recvBlock bool
recvErr error
}
func (f *fakeWSConn) HeartbeatLoop(ctx context.Context, _ time.Duration) error {
@@ -86,7 +89,7 @@ func (f *fakeWSConn) ReceiveLoop(ctx context.Context, onMessage func(map[string]
<-ctx.Done()
return ctx.Err()
}
return nil
return f.recvErr
}
func (f *fakeWSConn) Close() error {
@@ -274,12 +277,11 @@ func TestRun_DialFailureIncrementsFailures(t *testing.T) {
}
}
// TestRun_ReceiveLoopEndsTriggersReconnect ReceiveLoop 返回后 Run 应重连(再次拨号成功)。
// 断线后 retryDelay 默认 5s;token 冷却 1min 会阻塞第二次 refresh,测试期间后台重置冷却。
// TestRun_ReceiveLoopEndsTriggersReconnect 正常结束后直接重连,并复用当前内存 token。
func TestRun_ReceiveLoopEndsTriggersReconnect(t *testing.T) {
acc, _, _, cleanup := newRunAccount(t, &fakeRunMtop{token: "tok-1"})
mtopClient := &countingMtop{fakeRunMtop: fakeRunMtop{token: "tok-1"}}
acc, _, _, cleanup := newRunAccount(t, mtopClient)
defer cleanup()
acc.lastTokenRefresh = time.Time{}
conn1 := &fakeWSConn{recvBlock: false} // 立即返回,模拟断线
conn2 := &fakeWSConn{recvBlock: true} // 第二次连上后阻塞
@@ -288,25 +290,11 @@ func TestRun_ReceiveLoopEndsTriggersReconnect(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
// 后台重置 token 冷却,避免第二次 refreshToken sleep 1 分钟(仅测试用)。
go func() {
for {
select {
case <-ctx.Done():
return
case <-time.After(50 * time.Millisecond):
acc.mu.Lock()
acc.lastTokenRefresh = time.Time{}
acc.mu.Unlock()
}
}
}()
runDone := make(chan error, 1)
go func() { runDone <- acc.Run(ctx) }()
// 等待第二次拨号发生(首次断线后 retryDelay 5s + 重连)。
deadline := time.After(8 * time.Second)
// 正常 close 不计失败、也不退避。
deadline := time.After(2 * time.Second)
for {
d.mu.Lock()
calls := d.calls
@@ -316,7 +304,7 @@ func TestRun_ReceiveLoopEndsTriggersReconnect(t *testing.T) {
}
select {
case <-deadline:
t.Fatalf("Run 未在 8s 内重连,calls=%d", calls)
t.Fatalf("Run 未在 2s 内重连,calls=%d", calls)
default:
}
time.Sleep(100 * time.Millisecond)
@@ -328,6 +316,54 @@ func TestRun_ReceiveLoopEndsTriggersReconnect(t *testing.T) {
case <-time.After(3 * time.Second):
t.Fatal("重连后 ctx 取消 Run 未退出")
}
if calls := atomic.LoadInt32(&mtopClient.calls); calls != 1 {
t.Fatalf("正常重连应复用内存 token,不应重复请求 mtop: calls=%d", calls)
}
}
func TestRun_EstablishedNetworkErrorPreservesTokenAndCache(t *testing.T) {
mtopClient := &countingMtop{fakeRunMtop: fakeRunMtop{token: "tok-1"}}
acc, _, store, cleanup := newRunAccount(t, mtopClient)
defer cleanup()
conn := &fakeWSConn{recvErr: errors.New("connection reset by peer")}
acc.wsDialer = &fakeDialer{results: []dialResult{{conn: conn}}}
ctx, cancel := context.WithCancel(context.Background())
done := make(chan error, 1)
go func() { done <- acc.Run(ctx) }()
deadline := time.Now().Add(2 * time.Second)
for time.Now().Before(deadline) {
acc.mu.Lock()
failures := acc.networkFailures
acc.mu.Unlock()
if failures == 1 {
break
}
time.Sleep(10 * time.Millisecond)
}
acc.mu.Lock()
currentToken := acc.currentToken
networkFailures := acc.networkFailures
acc.mu.Unlock()
if networkFailures != 1 || currentToken != "tok-1" {
cancel()
<-done
t.Fatalf("网络断线不应清空内存 token: failures=%d token=%q", networkFailures, currentToken)
}
if cached, err := store.Tokens.Get(context.Background(), "cid"); err != nil || cached.AccessToken != "tok-1" {
cancel()
<-done
t.Fatalf("网络断线不应删除 token 缓存: cached=%+v err=%v", cached, err)
}
cancel()
select {
case <-done:
case <-time.After(2 * time.Second):
t.Fatal("取消后 Run 未退出")
}
if calls := atomic.LoadInt32(&mtopClient.calls); calls != 1 {
t.Fatalf("网络断线前只应获取一次 token: calls=%d", calls)
}
}
// TestRun_DisabledAccountExits 账号被禁用时 Run 立即退出。