chore: checkpoint repaired xianyu-go baseline
This commit is contained in:
1 parent
62705c524d
commit
3d37ff7917
119 files changed
+20086
-2085
No files matched your search
+205
-33
@@ -35,6 +35,16 @@ const (
|
||||
TokenRefreshMinGap = time.Minute
|
||||
MessageCooldown = 5 * time.Minute // 收到消息后 5 分钟内不刷 cookie
|
||||
PasswordLoginMinGap = 30 * time.Minute
|
||||
|
||||
// TokenCacheTTL 缓存的 accessToken 视为有效的时长。tokenRefreshLoop 每 15min
|
||||
// 刷新一次会续期该缓存;短重启 / 瞬时 mtop 失败时回退到此缓存不掉线。
|
||||
TokenCacheTTL = 90 * time.Minute
|
||||
// ShortConnectionThreshold 连接维持不足此时长视为短连接,疑似 token 失效,
|
||||
// 清除 token 缓存下轮重新派生,避免反复用失效缓存 token。
|
||||
ShortConnectionThreshold = 30 * time.Second
|
||||
// AuthExpiredRetryInterval 登录凭证失效且无法自动恢复时的慢重试间隔,
|
||||
// 保持 goroutine 存活,等用户重新扫码(DB cookie 更新后 reloadCookieFromDB 自愈)。
|
||||
AuthExpiredRetryInterval = 5 * time.Minute
|
||||
)
|
||||
|
||||
// 告警级别(OnAccountAlert 的 level 参数)。
|
||||
@@ -99,7 +109,7 @@ type Account struct {
|
||||
UserID string // unb(myid)
|
||||
|
||||
store *db.Store
|
||||
mtop *mtop.Client
|
||||
mtop mtop.Client
|
||||
wsDialer wsDialer
|
||||
handler Handler
|
||||
logger *slog.Logger
|
||||
@@ -117,7 +127,9 @@ type Account struct {
|
||||
runtimeUpdatedAt time.Time
|
||||
stopFn context.CancelFunc
|
||||
stopped bool
|
||||
conn *ws.Conn
|
||||
conn WSConn
|
||||
connStartedAt time.Time // 本次 WS 连接建立时间,用于短连接检测
|
||||
authExpiredAlerted bool // 已发过 auth_expired 告警,连接恢复后复位(避免刷屏)
|
||||
|
||||
// 去重
|
||||
dedupMu sync.Mutex
|
||||
@@ -139,14 +151,25 @@ type debounceEntry struct {
|
||||
deadline time.Time
|
||||
}
|
||||
|
||||
// WSConn 是 Account 对 ws 连接的最小契约。*ws.Conn 实现该接口;
|
||||
// 测试可注入 fakeWSConn 以隔离真实 WS 握手与网络。
|
||||
type WSConn interface {
|
||||
HeartbeatLoop(ctx context.Context, interval time.Duration) error
|
||||
ReceiveLoop(ctx context.Context, onMessage func(map[string]any)) error
|
||||
Close() error
|
||||
SetAccessToken(token string)
|
||||
SendText(ctx context.Context, myID, cid, toID, text string) error
|
||||
SendImage(ctx context.Context, myID, cid, toID, imageURL string, width, height int) error
|
||||
}
|
||||
|
||||
// wsDialer 抽象 ws.Dial,便于测试替身。
|
||||
type wsDialer interface {
|
||||
Dial(ctx context.Context, cfg ws.Config, logger *slog.Logger) (*ws.Conn, error)
|
||||
Dial(ctx context.Context, cfg ws.Config, logger *slog.Logger) (WSConn, error)
|
||||
}
|
||||
|
||||
type defaultDialer struct{}
|
||||
|
||||
func (defaultDialer) Dial(ctx context.Context, cfg ws.Config, logger *slog.Logger) (*ws.Conn, error) {
|
||||
func (defaultDialer) Dial(ctx context.Context, cfg ws.Config, logger *slog.Logger) (WSConn, error) {
|
||||
return ws.Dial(ctx, cfg, logger)
|
||||
}
|
||||
|
||||
@@ -157,6 +180,8 @@ type Config struct {
|
||||
Store *db.Store
|
||||
Handler Handler
|
||||
Logger *slog.Logger
|
||||
// MTop 可选:注入 mtop 客户端以便测试 mock。 nil 时使用默认 HTTP 实现。
|
||||
MTop mtop.Client
|
||||
}
|
||||
|
||||
// New 构造单账号运行时(未启动)。
|
||||
@@ -165,6 +190,10 @@ func New(cfg Config) *Account {
|
||||
if logger == nil {
|
||||
logger = slog.Default()
|
||||
}
|
||||
mtopClient := cfg.MTop
|
||||
if mtopClient == nil {
|
||||
mtopClient = mtop.NewClient()
|
||||
}
|
||||
cookies := protocol.TransCookies(cfg.CookieStr)
|
||||
myid := cookies["unb"]
|
||||
a := &Account{
|
||||
@@ -172,7 +201,7 @@ func New(cfg Config) *Account {
|
||||
CookieStr: cfg.CookieStr,
|
||||
UserID: myid,
|
||||
store: cfg.Store,
|
||||
mtop: &mtop.Client{},
|
||||
mtop: mtopClient,
|
||||
wsDialer: defaultDialer{},
|
||||
handler: cfg.Handler,
|
||||
logger: logger.With("account", cfg.CookieID),
|
||||
@@ -198,6 +227,9 @@ func (a *Account) Run(parent context.Context) error {
|
||||
a.stopFn = cancel
|
||||
a.mu.Unlock()
|
||||
|
||||
// 复用 DB 缓存的 device_id(跨进程重启稳定),避免每次重启换新设备 ID 触发风控。
|
||||
a.ensureDeviceIDCached(ctx)
|
||||
|
||||
for {
|
||||
if ctx.Err() != nil {
|
||||
return ctx.Err()
|
||||
@@ -208,18 +240,23 @@ func (a *Account) Run(parent context.Context) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// 1) 刷新 token。若服务端返回 session 过期,直接跳到密码登录刷新,
|
||||
// 不再空跑 5 次冷却重试。
|
||||
token, cookieStr, err := a.refreshToken(ctx)
|
||||
// 0) 复读 DB cookie:吸收外部更新(人工重新扫码 / refreshAccountProfile),
|
||||
// 让运行中账号无需 Manager.Restart 即可自愈。
|
||||
a.reloadCookieFromDB(ctx)
|
||||
|
||||
// 1) 取 token。缓存命中且未过期则跳过 mtop(降低风控 + 瞬时失败不掉线),
|
||||
// 否则刷新;刷新成功落库缓存。session 过期直接跳到慢重试兜底。
|
||||
token, cookieStr, err := a.acquireToken(ctx)
|
||||
if err != nil {
|
||||
a.logger.Error("刷新 token 失败", "err", err)
|
||||
a.logger.Error("获取 token 失败", "err", err)
|
||||
a.mu.Lock()
|
||||
a.connFailures++
|
||||
failures := a.connFailures
|
||||
a.mu.Unlock()
|
||||
a.setRuntimeError(ctx, err)
|
||||
if mtop.IsSessionExpiredErr(err) {
|
||||
a.logger.Warn("session 已失效,直接触发密码登录刷新", "err", err)
|
||||
a.logger.Warn("session 已失效,清除 token 缓存并进入慢重试", "err", err)
|
||||
a.clearTokenCache(ctx)
|
||||
a.alert(ctx, AlertLevelWarn, "账号 session 已失效",
|
||||
"登录凭证已被闲鱼服务端判定为失效,系统正在尝试通过浏览器密码登录自动恢复。若长时间未恢复,请人工处理。")
|
||||
if err := a.handleMaxFailures(ctx); err != nil {
|
||||
@@ -250,7 +287,7 @@ func (a *Account) Run(parent context.Context) error {
|
||||
var recorder func(direction, rawText, parsedJSON, parseStatus, errMsg string)
|
||||
if a.store != nil && a.store.WSMessages != nil {
|
||||
recorder = func(direction, rawText, parsedJSON, parseStatus, errMsg string) {
|
||||
_ = a.store.WSMessages.Add(context.Background(), db.WSMessage{
|
||||
if err := a.store.WSMessages.Add(context.Background(), db.WSMessage{
|
||||
CookieID: a.CookieID,
|
||||
Direction: direction,
|
||||
RawText: rawText,
|
||||
@@ -258,7 +295,9 @@ func (a *Account) Run(parent context.Context) error {
|
||||
MessageKind: "",
|
||||
ParseStatus: parseStatus,
|
||||
Error: errMsg,
|
||||
})
|
||||
}); err != nil {
|
||||
a.logger.Error("记录 WS 报文失败", "cookie_id", a.CookieID, "err", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
a.mu.Lock()
|
||||
@@ -290,15 +329,19 @@ func (a *Account) Run(parent context.Context) error {
|
||||
}
|
||||
a.mu.Lock()
|
||||
a.conn = conn
|
||||
a.connStartedAt = time.Now()
|
||||
a.authExpiredAlerted = false // 连接成功,复位 auth_expired 告警标记
|
||||
a.mu.Unlock()
|
||||
a.setRuntimeState(RuntimeOnline, "消息服务连接正常")
|
||||
|
||||
// 3) 心跳 + 消息接收,并并行运行 token 定时刷新。
|
||||
hbCtx, hbCancel := context.WithCancel(ctx)
|
||||
var hbErr error
|
||||
hbDone := make(chan struct{})
|
||||
go func() {
|
||||
hbErr = conn.HeartbeatLoop(hbCtx, HeartbeatInterval)
|
||||
hbCancel()
|
||||
close(hbDone)
|
||||
}()
|
||||
|
||||
refreshDone := make(chan struct{})
|
||||
@@ -310,15 +353,19 @@ func (a *Account) Run(parent context.Context) error {
|
||||
recvErr := conn.ReceiveLoop(ctx, a.dispatch)
|
||||
hbCancel()
|
||||
<-refreshDone
|
||||
<-hbDone // 确保 hbErr 写入完成后再读取(消除数据竞争)。
|
||||
_ = conn.Close()
|
||||
|
||||
// 连接结束:清 token,统计失败,决定重连或密码刷新。
|
||||
a.mu.Lock()
|
||||
startedAt := a.connStartedAt
|
||||
a.currentToken = ""
|
||||
a.conn = nil
|
||||
a.connFailures++
|
||||
failures := a.connFailures
|
||||
a.mu.Unlock()
|
||||
// 短连接:疑似 token 失效,清缓存下轮重新派生,避免反复用失效缓存 token。
|
||||
a.clearCacheIfShortConnection(ctx, startedAt)
|
||||
a.setRuntimeState(RuntimeReconnecting, "消息连接已断开,稍后自动重连")
|
||||
a.logger.Warn("WS 连接结束", "err", recvErr, "failures", failures, "heartbeat_err", hbErr)
|
||||
|
||||
@@ -391,10 +438,30 @@ func (a *Account) handleMaxFailures(ctx context.Context) error {
|
||||
return sleepCtx(ctx, 2*time.Second)
|
||||
}
|
||||
a.resetFailures()
|
||||
a.setRuntimeState(RuntimeAuthExpired, "登录凭证已失效,请重新扫码登录")
|
||||
a.alert(ctx, AlertLevelCritical, "账号自动恢复失败,需人工处理",
|
||||
fmt.Sprintf("账号 %s 连续失败 %d 次,浏览器密码登录刷新未能恢复登录凭证,账号已停止运行。请前往后台重新扫码授权或检查账号用户名/密码配置。", a.CookieID, MaxConnectionFailures))
|
||||
return fmt.Errorf("账号 %s 连续失败 %d 次且密码登录刷新失败,需重启实例", a.CookieID, MaxConnectionFailures)
|
||||
a.clearTokenCache(ctx)
|
||||
// 不再硬退出:进入慢重试,保持 goroutine 存活。用户重新扫码(DB cookie 更新)
|
||||
// 后,Run 顶部的 reloadCookieFromDB 会吸收新 cookie 并自愈回在线。
|
||||
a.setRuntimeState(RuntimeAuthExpired, "登录凭证已失效,自动慢重试中,重新扫码后自愈")
|
||||
if a.markAuthExpired() {
|
||||
a.alert(ctx, AlertLevelCritical, "账号自动恢复失败,需人工处理",
|
||||
fmt.Sprintf("账号 %s 连续失败 %d 次,登录凭证暂未自动恢复。账号将每 %v 慢重试一次,不会停止运行;前往后台重新扫码后无需手动重启即可自动恢复在线。", a.CookieID, MaxConnectionFailures, AuthExpiredRetryInterval))
|
||||
}
|
||||
if err := sleepCtx(ctx, AuthExpiredRetryInterval); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// markAuthExpired 标记进入 auth_expired 状态。仅在首次(未告警过)返回 true,
|
||||
// 连接恢复后由 Run 的 online 分支复位 authExpiredAlerted,避免重复告警刷屏。
|
||||
func (a *Account) markAuthExpired() bool {
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
if a.authExpiredAlerted {
|
||||
return false
|
||||
}
|
||||
a.authExpiredAlerted = true
|
||||
return true
|
||||
}
|
||||
|
||||
// alert 触发账号告警通知。handler 未注入或为 nil 时静默跳过。
|
||||
@@ -432,6 +499,8 @@ func (a *Account) retryDelay(errMsg string) time.Duration {
|
||||
}
|
||||
|
||||
// refreshToken 调 mtop token API,返回 (accessToken, 更新后的 cookie)。
|
||||
// 成功时把 token + device_id 缓存到 DB(saveTokenCache),供进程重启复用与
|
||||
// 稳态重连时跳过 mtop(acquireToken 命中缓存即直接返回)。
|
||||
func (a *Account) refreshToken(ctx context.Context) (string, string, error) {
|
||||
a.mu.Lock()
|
||||
cookieStr := a.CookieStr
|
||||
@@ -463,7 +532,9 @@ func (a *Account) refreshToken(ctx context.Context) (string, string, error) {
|
||||
cookieStr = res.UpdatedCookies
|
||||
if a.store != nil {
|
||||
if d, e := a.store.Cookies.GetDetails(ctx, a.CookieID); e == nil {
|
||||
_ = a.store.Cookies.Save(ctx, a.CookieID, res.UpdatedCookies, d.UserID)
|
||||
if err := a.store.Cookies.Save(ctx, a.CookieID, res.UpdatedCookies, d.UserID); err != nil {
|
||||
a.logger.Error("token 刷新后保存 cookie 失败", "cookie_id", a.CookieID, "err", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -473,26 +544,126 @@ func (a *Account) refreshToken(ctx context.Context) (string, string, error) {
|
||||
if res == nil {
|
||||
return "", "", fmt.Errorf("token API 未返回结果")
|
||||
}
|
||||
// 若 cookie 被刷新,持久化回数据库。
|
||||
if res.UpdatedCookies != cookieStr {
|
||||
a.mu.Lock()
|
||||
a.CookieStr = res.UpdatedCookies
|
||||
cookieStr = res.UpdatedCookies
|
||||
a.mu.Unlock()
|
||||
if a.store != nil {
|
||||
// 保留原 user_id:用 GetDetails 取后回写。
|
||||
if d, e := a.store.Cookies.GetDetails(ctx, a.CookieID); e == nil {
|
||||
_ = a.store.Cookies.Save(ctx, a.CookieID, res.UpdatedCookies, d.UserID)
|
||||
}
|
||||
}
|
||||
}
|
||||
a.saveTokenCache(ctx, deviceID, res.AccessToken)
|
||||
return res.AccessToken, cookieStr, nil
|
||||
}
|
||||
|
||||
// acquireToken 取用于 WS /reg 的 accessToken:缓存命中且未过期则跳过 mtop(降低风控
|
||||
// 与瞬时失败影响),否则调 refreshToken 重新派生并落库缓存。
|
||||
//
|
||||
// 设计:稳态重连时复用未过期缓存 token,避免每次重连都打 mtop(降低风控触发)。
|
||||
// 缓存 token 若已被服务端失效,dial 后会短连接断开 → clearTokenCache → 下轮重新派生,自愈。
|
||||
func (a *Account) acquireToken(ctx context.Context) (string, string, error) {
|
||||
if token, ok := a.cachedTokenIfFresh(ctx); ok {
|
||||
a.mu.Lock()
|
||||
a.currentToken = token
|
||||
cookieStr := a.CookieStr
|
||||
a.mu.Unlock()
|
||||
a.logger.Info("使用缓存的 accessToken,跳过 mtop 刷新")
|
||||
return token, cookieStr, nil
|
||||
}
|
||||
return a.refreshToken(ctx)
|
||||
}
|
||||
|
||||
// cachedTokenIfFresh 返回未过期的缓存 accessToken。无缓存 / 已过期返回 ok=false。
|
||||
func (a *Account) cachedTokenIfFresh(ctx context.Context) (string, bool) {
|
||||
if a.store == nil || a.store.Tokens == nil {
|
||||
return "", false
|
||||
}
|
||||
tk, err := a.store.Tokens.Get(ctx, a.CookieID)
|
||||
if err != nil {
|
||||
return "", false
|
||||
}
|
||||
if tk.AccessToken == "" || tk.ExpireAt <= time.Now().Unix() {
|
||||
return "", false
|
||||
}
|
||||
// 命中缓存时同步复用其 device_id,保证 token 与 /reg.did 一致。
|
||||
if tk.DeviceID != "" {
|
||||
a.mu.Lock()
|
||||
a.deviceID = tk.DeviceID
|
||||
a.mu.Unlock()
|
||||
}
|
||||
return tk.AccessToken, true
|
||||
}
|
||||
|
||||
// ensureDeviceIDCached 优先复用 DB 中的 device_id;无缓存则持久化当前生成的 device_id,
|
||||
// 供后续进程重启复用。这是 device_id 跨重启稳定的关键。
|
||||
func (a *Account) ensureDeviceIDCached(ctx context.Context) {
|
||||
if a.store == nil || a.store.Tokens == nil {
|
||||
return
|
||||
}
|
||||
if tk, err := a.store.Tokens.Get(ctx, a.CookieID); err == nil && tk.DeviceID != "" {
|
||||
a.mu.Lock()
|
||||
a.deviceID = tk.DeviceID
|
||||
a.mu.Unlock()
|
||||
return
|
||||
}
|
||||
a.mu.Lock()
|
||||
did := a.deviceID
|
||||
a.mu.Unlock()
|
||||
if did == "" {
|
||||
return
|
||||
}
|
||||
if err := a.store.Tokens.Save(ctx, a.CookieID, did, "", 0); err != nil {
|
||||
a.logger.Warn("持久化 device_id 失败", "err", err)
|
||||
}
|
||||
}
|
||||
|
||||
// saveTokenCache 把 accessToken + device_id 缓存到 DB(expire_at = now + TokenCacheTTL)。
|
||||
func (a *Account) saveTokenCache(ctx context.Context, deviceID, accessToken string) {
|
||||
if a.store == nil || a.store.Tokens == nil || accessToken == "" {
|
||||
return
|
||||
}
|
||||
if err := a.store.Tokens.Save(ctx, a.CookieID, deviceID, accessToken, time.Now().Add(TokenCacheTTL).Unix()); err != nil {
|
||||
a.logger.Warn("缓存 accessToken 失败", "err", err)
|
||||
}
|
||||
}
|
||||
|
||||
// clearTokenCache 清除账号 token 缓存(session 失效 / 短连接可疑 / cookie 被外部更新时调用)。
|
||||
func (a *Account) clearTokenCache(ctx context.Context) {
|
||||
if a.store == nil || a.store.Tokens == nil {
|
||||
return
|
||||
}
|
||||
if err := a.store.Tokens.Clear(ctx, a.CookieID); err != nil {
|
||||
a.logger.Warn("清除 token 缓存失败", "err", err)
|
||||
}
|
||||
}
|
||||
|
||||
// reloadCookieFromDB 复读 DB cookie:与内存不同则采纳,并清 token 缓存(新 cookie 对应
|
||||
// 新 session,旧 token 作废)。让运行中账号吸收外部更新(人工重新扫码 / refreshAccountProfile)。
|
||||
func (a *Account) reloadCookieFromDB(ctx context.Context) {
|
||||
if a.store == nil || a.store.Cookies == nil {
|
||||
return
|
||||
}
|
||||
d, err := a.store.Cookies.GetDetails(ctx, a.CookieID)
|
||||
if err != nil || d == nil || d.Value == "" {
|
||||
return
|
||||
}
|
||||
a.mu.Lock()
|
||||
cur := a.CookieStr
|
||||
a.mu.Unlock()
|
||||
if d.Value == cur {
|
||||
return
|
||||
}
|
||||
a.logger.Info("检测到 DB cookie 已更新,重新加载", "account", a.CookieID)
|
||||
a.replaceCookieStr(d.Value)
|
||||
a.clearTokenCache(ctx)
|
||||
}
|
||||
|
||||
// clearCacheIfShortConnection 连接维持不足 ShortConnectionThreshold 视为短连接,
|
||||
// 疑似 token 失效,清除 token 缓存让下轮重新派生。
|
||||
func (a *Account) clearCacheIfShortConnection(ctx context.Context, startedAt time.Time) {
|
||||
if startedAt.IsZero() || time.Since(startedAt) >= ShortConnectionThreshold {
|
||||
return
|
||||
}
|
||||
a.logger.Warn("连接维持过短,疑似 token 失效,清除 token 缓存", "duration", time.Since(startedAt).Round(time.Second))
|
||||
a.clearTokenCache(ctx)
|
||||
}
|
||||
|
||||
// tokenRefreshLoop 在 WS 在线期间按 TokenRefreshInterval 定时刷新 token。
|
||||
// 刷新失败不重连(让心跳/接收循环去判定),仅记录日志;session 过期会触发
|
||||
// 接收循环断开,主循环再走 handleMaxFailures 兜底。
|
||||
func (a *Account) tokenRefreshLoop(ctx context.Context, conn *ws.Conn) {
|
||||
func (a *Account) tokenRefreshLoop(ctx context.Context, conn WSConn) {
|
||||
ticker := time.NewTicker(TokenRefreshInterval)
|
||||
defer ticker.Stop()
|
||||
for {
|
||||
@@ -508,7 +679,8 @@ func (a *Account) tokenRefreshLoop(ctx context.Context, conn *ws.Conn) {
|
||||
if err != nil {
|
||||
a.logger.Warn("定时刷新 token 失败", "err", err)
|
||||
if mtop.IsSessionExpiredErr(err) {
|
||||
// session 失效:让接收循环尽快断开走兜底,主动关闭连接。
|
||||
// session 失效:清缓存,让接收循环尽快断开走兜底,主动关闭连接。
|
||||
a.clearTokenCache(ctx)
|
||||
_ = conn.Close()
|
||||
return
|
||||
}
|
||||
@@ -594,7 +766,7 @@ func (a *Account) SendImage(ctx context.Context, chatID, toUserID, imageURL stri
|
||||
return conn.SendImage(sendCtx, myID, chatID, toUserID, imageURL, 800, 600)
|
||||
}
|
||||
|
||||
func (a *Account) currentSenderState() (*ws.Conn, string, error) {
|
||||
func (a *Account) currentSenderState() (WSConn, string, error) {
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
if a.conn == nil {
|
||||
|
||||
@@ -0,0 +1,571 @@
|
||||
package engine
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"xianyu-go/internal/automation"
|
||||
)
|
||||
|
||||
// TestStop_IdempotentAndClearsTimers Stop 重复调用幂等;调用后防抖定时器被清空。
|
||||
func TestStop_IdempotentAndClearsTimers(t *testing.T) {
|
||||
acc, _, _, cleanup := newAccountForTest(t)
|
||||
defer cleanup()
|
||||
|
||||
// 调度一个防抖定时器,验证 Stop 会清空。
|
||||
chat := ChatMessage{AccountID: "cid", ChatID: "c1", Text: "hi"}
|
||||
acc.scheduleDebouncedReply(chat)
|
||||
acc.debounceMu.Lock()
|
||||
if len(acc.debounceTimers) != 1 {
|
||||
t.Fatalf("应有 1 个定时器,got %d", len(acc.debounceTimers))
|
||||
}
|
||||
acc.debounceMu.Unlock()
|
||||
|
||||
acc.Stop()
|
||||
status := acc.RuntimeStatus()
|
||||
if status.State != RuntimeStopped {
|
||||
t.Errorf("state=%q want %q", status.State, RuntimeStopped)
|
||||
}
|
||||
acc.debounceMu.Lock()
|
||||
timers := len(acc.debounceTimers)
|
||||
acc.debounceMu.Unlock()
|
||||
if timers != 0 {
|
||||
t.Errorf("Stop 应清空防抖定时器,剩 %d", timers)
|
||||
}
|
||||
|
||||
// 重复 Stop 幂等,不 panic。
|
||||
acc.Stop()
|
||||
acc.Stop()
|
||||
if acc.RuntimeStatus().State != RuntimeStopped {
|
||||
t.Error("重复 Stop 后状态应仍为 stopped")
|
||||
}
|
||||
}
|
||||
|
||||
// TestStop_CancelFunc_WhenNil stopFn 为 nil 时不 panic(未启动 Run 的账号也能 Stop)。
|
||||
func TestStop_CancelFunc_WhenNil(t *testing.T) {
|
||||
acc, _, _, cleanup := newAccountForTest(t)
|
||||
defer cleanup()
|
||||
if acc.stopFn != nil {
|
||||
t.Fatal("未启动 Run 时 stopFn 应为 nil")
|
||||
}
|
||||
// 不应 panic。
|
||||
acc.Stop()
|
||||
}
|
||||
|
||||
// TestRuntimeStatus_ConnectedRequiresOnlineAndConn conn 为 nil 或状态非 online 时 Connected=false。
|
||||
func TestRuntimeStatus_ConnectedRequiresOnlineAndConn(t *testing.T) {
|
||||
acc, _, _, cleanup := newAccountForTest(t)
|
||||
defer cleanup()
|
||||
|
||||
// 初始:starting,无 conn,Connected=false。
|
||||
s := acc.RuntimeStatus()
|
||||
if s.Connected || s.State != RuntimeStarting {
|
||||
t.Fatalf("初始状态异常: %+v", s)
|
||||
}
|
||||
if s.Failures != 0 || s.Message == "" {
|
||||
t.Fatalf("Failures/Message 异常: %+v", s)
|
||||
}
|
||||
if s.UpdatedAt.IsZero() {
|
||||
t.Error("UpdatedAt 应已设置")
|
||||
}
|
||||
|
||||
// 设为 online 但无 conn:仍不算 Connected。
|
||||
acc.setRuntimeState(RuntimeOnline, "在线")
|
||||
if acc.RuntimeStatus().Connected {
|
||||
t.Error("无 conn 时 Connected 应为 false")
|
||||
}
|
||||
|
||||
// 设为 reconnecting:Connected=false。
|
||||
acc.setRuntimeState(RuntimeReconnecting, "重连中")
|
||||
if acc.RuntimeStatus().Connected {
|
||||
t.Error("reconnecting 状态 Connected 应为 false")
|
||||
}
|
||||
}
|
||||
|
||||
// alertCountingHandler 包装 recordingHandler 并原子统计告警次数。
|
||||
type alertCountingHandler struct {
|
||||
recordingHandler
|
||||
alerts int32
|
||||
}
|
||||
|
||||
func (a *alertCountingHandler) OnAccountAlert(_ context.Context, _, level, _, _ string) {
|
||||
if level == AlertLevelWarn {
|
||||
atomic.AddInt32(&a.alerts, 1)
|
||||
}
|
||||
}
|
||||
|
||||
// TestSetRuntimeError_AllBranches 覆盖验证/captcha、token 失效、默认重连三分支
|
||||
// 及告警去重逻辑(仅从非验证态进入验证态时告警一次)。
|
||||
func TestSetRuntimeError_AllBranches(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
|
||||
// 1) captcha/risk 关键词 → VerificationRequired,且从非验证态进入时告警一次。
|
||||
t.Run("captcha", func(t *testing.T) {
|
||||
acc, _, _, cleanup := newAccountForTest(t)
|
||||
defer cleanup()
|
||||
h := &alertCountingHandler{}
|
||||
acc.handler = h
|
||||
acc.setRuntimeError(ctx, fmt.Errorf("FAIL_SYS_USER_VALIDATE: captcha required"))
|
||||
if s := acc.RuntimeStatus(); s.State != RuntimeVerificationRequired {
|
||||
t.Fatalf("state=%q", s.State)
|
||||
}
|
||||
if got := atomic.LoadInt32(&h.alerts); got != 1 {
|
||||
t.Errorf("首次进入验证态应告警一次,got %d want 1", got)
|
||||
}
|
||||
// 再次以验证错误进入:不应重复告警(prev 已是 verification)。
|
||||
acc.setRuntimeError(ctx, fmt.Errorf("rgv587 风控"))
|
||||
if got := atomic.LoadInt32(&h.alerts); got != 1 {
|
||||
t.Errorf("验证态重复进入不应重复告警,got %d want 1", got)
|
||||
}
|
||||
})
|
||||
|
||||
// 2) token expired 关键词 → AuthExpired(不告警)。
|
||||
t.Run("token_expired", func(t *testing.T) {
|
||||
acc, _, _, cleanup := newAccountForTest(t)
|
||||
defer cleanup()
|
||||
h := &alertCountingHandler{}
|
||||
acc.handler = h
|
||||
for _, msg := range []string{
|
||||
"登录凭证已失效",
|
||||
"FAIL_SYS_TOKEN_EXOIRED",
|
||||
"FAIL_SYS_TOKEN_EXPIRED",
|
||||
"cookie 缺少 unb",
|
||||
} {
|
||||
acc.setRuntimeError(ctx, errors.New(msg))
|
||||
if s := acc.RuntimeStatus(); s.State != RuntimeAuthExpired {
|
||||
t.Fatalf("msg=%q state=%q want %q", msg, s.State, RuntimeAuthExpired)
|
||||
}
|
||||
}
|
||||
if got := atomic.LoadInt32(&h.alerts); got != 0 {
|
||||
t.Errorf("token 失效分支不应触发 warn 告警,got %d", got)
|
||||
}
|
||||
})
|
||||
|
||||
// 3) 其他错误 → Reconnecting(不告警)。
|
||||
t.Run("other", func(t *testing.T) {
|
||||
acc, _, _, cleanup := newAccountForTest(t)
|
||||
defer cleanup()
|
||||
h := &alertCountingHandler{}
|
||||
acc.handler = h
|
||||
acc.setRuntimeError(ctx, errors.New("connection refused"))
|
||||
if s := acc.RuntimeStatus(); s.State != RuntimeReconnecting {
|
||||
t.Fatalf("state=%q want %q", s.State, RuntimeReconnecting)
|
||||
}
|
||||
if got := atomic.LoadInt32(&h.alerts); got != 0 {
|
||||
t.Errorf("默认分支不应告警,got %d", got)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// TestAlert_NilHandler handler 为 nil 时静默跳过,不 panic。
|
||||
func TestAlert_NilHandler(t *testing.T) {
|
||||
acc, _, _, cleanup := newAccountForTest(t)
|
||||
defer cleanup()
|
||||
acc.handler = nil
|
||||
// 不应 panic。
|
||||
acc.alert(context.Background(), AlertLevelCritical, "title", "body")
|
||||
}
|
||||
|
||||
// TestResetFailures 重置失败计数。
|
||||
func TestResetFailures(t *testing.T) {
|
||||
acc, _, _, cleanup := newAccountForTest(t)
|
||||
defer cleanup()
|
||||
acc.connFailures = 7
|
||||
acc.resetFailures()
|
||||
if acc.connFailures != 0 {
|
||||
t.Errorf("resetFailures 后 connFailures=%d want 0", acc.connFailures)
|
||||
}
|
||||
}
|
||||
|
||||
// TestRetryDelay_FailureClampsAtOne connFailures=0 时按 1 计算。
|
||||
func TestRetryDelay_FailureClampsAtOne(t *testing.T) {
|
||||
acc, _, _, cleanup := newAccountForTest(t)
|
||||
defer cleanup()
|
||||
acc.connFailures = 0
|
||||
// close-frame:min(3*1,15)=3s。
|
||||
if d := acc.retryDelay("no close frame received or sent"); d != 3*time.Second {
|
||||
t.Errorf("failures=0 clamp to 1: got %v want 3s", d)
|
||||
}
|
||||
// timeout:min(10*1,60)=10s。
|
||||
if d := acc.retryDelay("timeout reading"); d != 10*time.Second {
|
||||
t.Errorf("timeout failures=0: got %v want 10s", d)
|
||||
}
|
||||
// default:min(5*1,30)=5s。
|
||||
if d := acc.retryDelay("random error"); d != 5*time.Second {
|
||||
t.Errorf("default failures=0: got %v want 5s", d)
|
||||
}
|
||||
}
|
||||
|
||||
// TestRetryDelay_TimeoutVariant "timeout" 关键词分支。
|
||||
func TestRetryDelay_TimeoutVariant(t *testing.T) {
|
||||
acc, _, _, cleanup := newAccountForTest(t)
|
||||
defer cleanup()
|
||||
acc.connFailures = 3
|
||||
// min(10*3,60)=30s。
|
||||
if d := acc.retryDelay("dial timeout"); d != 30*time.Second {
|
||||
t.Errorf("timeout failures=3: got %v want 30s", d)
|
||||
}
|
||||
acc.connFailures = 10
|
||||
if d := acc.retryDelay("timeout"); d != 60*time.Second {
|
||||
t.Errorf("timeout failures=10 cap: got %v want 60s", d)
|
||||
}
|
||||
}
|
||||
|
||||
// TestHandleMaxFailures_RecentMessageSkipPasswordLogin 最近仍收到消息时跳过密码登录刷新,
|
||||
// 重置失败计数并返回 nil(睡眠时间可被 ctx 取消)。
|
||||
func TestHandleMaxFailures_RecentMessageSkipPasswordLogin(t *testing.T) {
|
||||
acc, h, _, cleanup := newAccountForTest(t)
|
||||
defer cleanup()
|
||||
ctx := context.Background()
|
||||
|
||||
// 设最近收到消息(在 MessageCooldown 内)。
|
||||
acc.mu.Lock()
|
||||
acc.lastMsgReceived = time.Now()
|
||||
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())
|
||||
}
|
||||
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 acc.connFailures != 0 {
|
||||
t.Errorf("应重置失败计数,got %d", acc.connFailures)
|
||||
}
|
||||
}
|
||||
|
||||
// TestHandleMaxFailures_PasswordLoginSuccess 密码登录刷新成功:重置失败计数、状态置 connecting、cookie 更新。
|
||||
func TestHandleMaxFailures_PasswordLoginSuccess(t *testing.T) {
|
||||
acc, h, store, cleanup := newAccountForTest(t)
|
||||
defer cleanup()
|
||||
ctx := context.Background()
|
||||
|
||||
// 无最近消息、未在密码登录冷却中。
|
||||
acc.mu.Lock()
|
||||
acc.lastMsgReceived = time.Time{}
|
||||
acc.lastPasswordLogin = time.Time{}
|
||||
acc.connFailures = MaxConnectionFailures
|
||||
acc.mu.Unlock()
|
||||
|
||||
// handler.OnPasswordLoginRefresh 返回 true → 成功路径。
|
||||
// store.Cookies.GetDetails 返回新 cookie,应触发 replaceCookieStr。
|
||||
newCookie := "unb=999; _m_h5_tk=tk_new;"
|
||||
admin, err := store.Users.GetByUsername(ctx, "admin")
|
||||
if err != nil {
|
||||
t.Fatalf("GetByUsername: %v", err)
|
||||
}
|
||||
if err := store.Cookies.Save(ctx, "cid", newCookie, admin.ID); err != nil {
|
||||
t.Fatalf("Save: %v", err)
|
||||
}
|
||||
// 确认 GetDetails 能读到新值(排除 Save 静默失败)。
|
||||
d, err := store.Cookies.GetDetails(ctx, "cid")
|
||||
if err != nil || d.Value != newCookie {
|
||||
t.Fatalf("GetDetails 未返回新 cookie: d=%+v err=%v", d, err)
|
||||
}
|
||||
|
||||
// 用一个延迟取消的 ctx:GetDetails 能成功完成,sleepCtx(2s) 会在取消时返回 ctx.Err()。
|
||||
cctx, cancel := context.WithTimeout(ctx, 50*time.Millisecond)
|
||||
defer cancel()
|
||||
err = acc.handleMaxFailures(cctx)
|
||||
// 成功刷新后进入 sleepCtx(2s),超时 ctx 让其返回 ctx.Err()。
|
||||
if err != cctx.Err() {
|
||||
t.Fatalf("成功路径 sleepCtx 应返回 ctx.Err(),got %v want %v", err, cctx.Err())
|
||||
}
|
||||
if h.refresh != 1 {
|
||||
t.Errorf("应调用一次 OnPasswordLoginRefresh,got %d", h.refresh)
|
||||
}
|
||||
if acc.connFailures != 0 {
|
||||
t.Errorf("应重置失败计数,got %d", acc.connFailures)
|
||||
}
|
||||
if s := acc.RuntimeStatus(); s.State != RuntimeConnecting {
|
||||
t.Errorf("状态应为 connecting,got %q", s.State)
|
||||
}
|
||||
// replaceCookieStr 应已更新 cookie。
|
||||
if got := acc.currentCookieStr(); got != newCookie {
|
||||
t.Errorf("cookie 未更新: got %q want %q", got, newCookie)
|
||||
}
|
||||
}
|
||||
|
||||
// failingRefreshHandler OnPasswordLoginRefresh 返回 false 的 handler,记录告警。
|
||||
type failingRefreshHandler struct {
|
||||
alerts []string
|
||||
}
|
||||
|
||||
func (f *failingRefreshHandler) HandleChatMessage(context.Context, ChatMessage) error { return nil }
|
||||
func (f *failingRefreshHandler) HandleSystemEvent(context.Context, automation.Task) error {
|
||||
return nil
|
||||
}
|
||||
func (f *failingRefreshHandler) OnPasswordLoginRefresh(context.Context, string) bool { return false }
|
||||
func (f *failingRefreshHandler) OnAccountAlert(_ context.Context, _, level, _, _ string) {
|
||||
f.alerts = append(f.alerts, level)
|
||||
}
|
||||
|
||||
// TestHandleMaxFailures_PasswordLoginFailure 密码登录刷新失败:不再硬退出,进入慢重试,
|
||||
// 状态 AuthExpired,触发一次 critical 告警。
|
||||
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()
|
||||
|
||||
// handler 返回 false → 刷新失败。
|
||||
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())
|
||||
}
|
||||
if s := acc.RuntimeStatus(); s.State != RuntimeAuthExpired {
|
||||
t.Errorf("状态应为 auth_expired,got %q", s.State)
|
||||
}
|
||||
if len(h.alerts) != 1 || h.alerts[0] != AlertLevelCritical {
|
||||
t.Errorf("应触发一次 critical 告警,got %+v", h.alerts)
|
||||
}
|
||||
}
|
||||
|
||||
// TestReplaceCookieStr_UpdateUserIDAndDeviceID 更新 cookie 后 unb 变化时重置 deviceID。
|
||||
func TestReplaceCookieStr_UpdateUserIDAndDeviceID(t *testing.T) {
|
||||
acc, _, _, cleanup := newAccountForTest(t)
|
||||
defer cleanup()
|
||||
|
||||
// 初始:UserID=123,deviceID 已由 New 生成。
|
||||
acc.mu.Lock()
|
||||
oldDevice := acc.deviceID
|
||||
oldUser := acc.UserID
|
||||
acc.mu.Unlock()
|
||||
if oldUser != "123" {
|
||||
t.Fatalf("初始 UserID=%q want 123", oldUser)
|
||||
}
|
||||
if oldDevice == "" {
|
||||
t.Fatal("初始 deviceID 不应为空")
|
||||
}
|
||||
|
||||
// 更新为新 unb。
|
||||
acc.replaceCookieStr("unb=456; _m_h5_tk=tk2;")
|
||||
acc.mu.Lock()
|
||||
newDevice := acc.deviceID
|
||||
newUser := acc.UserID
|
||||
newCookie := acc.CookieStr
|
||||
acc.mu.Unlock()
|
||||
if newUser != "456" {
|
||||
t.Errorf("UserID 未更新: got %q want 456", newUser)
|
||||
}
|
||||
if newDevice == "" {
|
||||
t.Error("deviceID 不应为空")
|
||||
}
|
||||
// 不同 unb 应重新生成 deviceID(基于 unb 的哈希)。
|
||||
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) {
|
||||
acc, _, _, cleanup := newAccountForTest(t)
|
||||
defer cleanup()
|
||||
// 清空 deviceID 与 UserID,模拟异常状态。
|
||||
acc.mu.Lock()
|
||||
acc.deviceID = ""
|
||||
acc.UserID = ""
|
||||
acc.mu.Unlock()
|
||||
|
||||
acc.replaceCookieStr("unb=789; _m_h5_tk=tk3;")
|
||||
acc.mu.Lock()
|
||||
d := acc.deviceID
|
||||
u := acc.UserID
|
||||
acc.mu.Unlock()
|
||||
if u != "789" {
|
||||
t.Errorf("UserID=%q want 789", u)
|
||||
}
|
||||
if d == "" {
|
||||
t.Error("deviceID 应兜底生成")
|
||||
}
|
||||
}
|
||||
|
||||
// TestReplaceCookieStr_NoUnbNoChange cookie 无 unb 时只更新 CookieStr。
|
||||
func TestReplaceCookieStr_NoUnbNoChange(t *testing.T) {
|
||||
acc, _, _, cleanup := newAccountForTest(t)
|
||||
defer cleanup()
|
||||
acc.mu.Lock()
|
||||
oldDevice := acc.deviceID
|
||||
oldUser := acc.UserID
|
||||
acc.mu.Unlock()
|
||||
|
||||
acc.replaceCookieStr("foo=bar; baz=qux;")
|
||||
acc.mu.Lock()
|
||||
d := acc.deviceID
|
||||
u := acc.UserID
|
||||
c := acc.CookieStr
|
||||
acc.mu.Unlock()
|
||||
if u != oldUser {
|
||||
t.Errorf("无 unb 时 UserID 不应变: got %q want %q", u, oldUser)
|
||||
}
|
||||
if d != oldDevice {
|
||||
t.Errorf("无 unb 时 deviceID 不应变: got %q want %q", d, oldDevice)
|
||||
}
|
||||
if c != "foo=bar; baz=qux;" {
|
||||
t.Errorf("CookieStr 未更新: got %q", c)
|
||||
}
|
||||
}
|
||||
|
||||
// TestUpdateCookie_IgnoresEmpty 纯空白/空字符串被忽略,不覆盖现有 cookie。
|
||||
func TestUpdateCookie_IgnoresEmpty(t *testing.T) {
|
||||
acc, _, _, cleanup := newAccountForTest(t)
|
||||
defer cleanup()
|
||||
orig := acc.currentCookieStr()
|
||||
|
||||
// 空字符串与纯空白(TrimSpace 后为空)应被忽略。
|
||||
acc.UpdateCookie("")
|
||||
acc.UpdateCookie(" ")
|
||||
acc.UpdateCookie("\t\n")
|
||||
if got := acc.currentCookieStr(); got != orig {
|
||||
t.Errorf("空白 cookie 不应更新: got %q want %q", got, orig)
|
||||
}
|
||||
|
||||
// 非空(即使含首尾空白)应原样存储——UpdateCookie 只做空值检查,不做 trim。
|
||||
acc.UpdateCookie("unb=123; _m_h5_tk=tk_new;")
|
||||
if got := acc.currentCookieStr(); got != "unb=123; _m_h5_tk=tk_new;" {
|
||||
t.Errorf("非空 cookie 应更新: got %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
// TestCurrentCookieStr 线程安全返回当前 CookieStr。
|
||||
func TestCurrentCookieStr(t *testing.T) {
|
||||
acc, _, _, cleanup := newAccountForTest(t)
|
||||
defer cleanup()
|
||||
if got := acc.currentCookieStr(); got != "unb=123; _m_h5_tk=tk_1;" {
|
||||
t.Errorf("currentCookieStr=%q", got)
|
||||
}
|
||||
acc.UpdateCookie("unb=1; x=2;")
|
||||
if got := acc.currentCookieStr(); got != "unb=1; x=2;" {
|
||||
t.Errorf("更新后 currentCookieStr=%q", got)
|
||||
}
|
||||
}
|
||||
|
||||
// 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。
|
||||
if err := sleepCtx(context.Background(), 0); err != nil {
|
||||
t.Errorf("d=0 应返回 nil,got %v", err)
|
||||
}
|
||||
if err := sleepCtx(context.Background(), -time.Second); err != nil {
|
||||
t.Errorf("d<0 应返回 nil,got %v", err)
|
||||
}
|
||||
|
||||
// 正常短睡眠。
|
||||
start := time.Now()
|
||||
if err := sleepCtx(context.Background(), 50*time.Millisecond); err != nil {
|
||||
t.Errorf("正常睡眠应返回 nil,got %v", err)
|
||||
}
|
||||
if elapsed := time.Since(start); elapsed < 40*time.Millisecond {
|
||||
t.Errorf("睡眠时间过短: %v", elapsed)
|
||||
}
|
||||
|
||||
// ctx 取消:应立即返回 ctx.Err()。
|
||||
cctx, cancel := context.WithCancel(context.Background())
|
||||
go func() {
|
||||
time.Sleep(20 * time.Millisecond)
|
||||
cancel()
|
||||
}()
|
||||
start = time.Now()
|
||||
err := sleepCtx(cctx, 5*time.Second)
|
||||
if err != cctx.Err() {
|
||||
t.Errorf("sleepCtx 取消应返回 ctx.Err(): got %v want %v", err, cctx.Err())
|
||||
}
|
||||
if elapsed := time.Since(start); elapsed > time.Second {
|
||||
t.Errorf("ctx 取消应立即返回,耗时 %v", elapsed)
|
||||
}
|
||||
}
|
||||
|
||||
// TestErrString errString 处理 nil 与非 nil。
|
||||
func TestErrString(t *testing.T) {
|
||||
if got := errString(nil); got != "" {
|
||||
t.Errorf("errString(nil)=%q want empty", got)
|
||||
}
|
||||
e := errors.New("boom")
|
||||
if got := errString(e); got != "boom" {
|
||||
t.Errorf("errString=%q want boom", got)
|
||||
}
|
||||
}
|
||||
|
||||
// TestTruncID 长串截断、短串原样。
|
||||
func TestTruncID(t *testing.T) {
|
||||
short := "abc123"
|
||||
if got := truncID(short); got != short {
|
||||
t.Errorf("短串应原样返回: got %q", got)
|
||||
}
|
||||
long := ""
|
||||
for i := 0; i < 80; i++ {
|
||||
long += "x"
|
||||
}
|
||||
got := truncID(long)
|
||||
if len(got) != 53 || got[50:] != "..." {
|
||||
t.Errorf("长串应截断到 53 字符并加 ...: got %q (len=%d)", got, len(got))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,218 @@
|
||||
package engine
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"xianyu-go/internal/db"
|
||||
)
|
||||
|
||||
// TestBuildSystemPrompt 自定义 prompt 替换 {item_title};默认模板含商品信息与折扣上限。
|
||||
func TestBuildSystemPrompt(t *testing.T) {
|
||||
// 自定义 prompt 优先,仅替换 {item_title}。
|
||||
got := buildSystemPrompt("你是卖{item_title}的客服", "iPhone", 0, "", 0, 0)
|
||||
if got != "你是卖iPhone的客服" {
|
||||
t.Fatalf("自定义 prompt 替换: got %q", got)
|
||||
}
|
||||
|
||||
// 默认模板:折扣上限 <=0 时兜底 10% / 100 元。
|
||||
got = buildSystemPrompt("", "会员卡", 9.9, "月卡", 0, 0)
|
||||
if !strings.Contains(got, "标题:会员卡") || !strings.Contains(got, "价格:9.90 元") {
|
||||
t.Fatalf("默认模板缺商品信息: %q", got)
|
||||
}
|
||||
if !strings.Contains(got, "最多优惠 10% 或 100 元") {
|
||||
t.Fatalf("默认折扣上限未兜底: %q", got)
|
||||
}
|
||||
|
||||
// 显式折扣上限。
|
||||
got = buildSystemPrompt("", "会员卡", 9.9, "月卡", 20, 50)
|
||||
if !strings.Contains(got, "最多优惠 20% 或 50 元") {
|
||||
t.Fatalf("显式折扣上限: %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
// newAIStore 构造一个带 admin + cookie 的测试 store,供 AIReplier 使用。
|
||||
func newAIStore(t *testing.T) (*db.Store, func()) {
|
||||
t.Helper()
|
||||
d, _, err := db.Open(context.Background(), filepath.Join(t.TempDir(), "ai.db"))
|
||||
if err != nil {
|
||||
t.Fatalf("Open: %v", err)
|
||||
}
|
||||
s := db.NewStore(d, db.DialectSQLite)
|
||||
ctx := context.Background()
|
||||
s.Users.Create(ctx, "admin", "[email protected]", "pw")
|
||||
admin, _ := s.Users.GetByUsername(ctx, "admin")
|
||||
s.Cookies.Save(ctx, "cid", "unb=1; _m_h5_tk=tk;", admin.ID)
|
||||
return s, func() { d.Close() }
|
||||
}
|
||||
|
||||
// TestAIReply_DisabledReturnsNil AI 未启用 / 无 APIKey 时应返回 nil,nil(降级到下一级)。
|
||||
func TestAIReply_DisabledReturnsNil(t *testing.T) {
|
||||
s, cleanup := newAIStore(t)
|
||||
defer cleanup()
|
||||
ctx := context.Background()
|
||||
a := NewAIReplier("cid", s, nil)
|
||||
|
||||
// 无配置记录 → 未启用 → nil。
|
||||
res, err := a.Reply(ctx, chatMsg("在吗", "item1", "chat1"))
|
||||
if err != nil || res != nil {
|
||||
t.Fatalf("未配置应返回 nil,nil: res=%+v err=%v", res, err)
|
||||
}
|
||||
|
||||
// 配置但 ai_enabled=0 → nil。
|
||||
s.DB.ExecContext(ctx, `INSERT INTO ai_reply_settings (cookie_id, ai_enabled, custom_prompts) VALUES ('cid', 0, '')`)
|
||||
res, err = a.Reply(ctx, chatMsg("在吗", "item1", "chat1"))
|
||||
if err != nil || res != nil {
|
||||
t.Fatalf("未启用应返回 nil,nil: res=%+v err=%v", res, err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestAIReply_NoAPIKeyReturnsNil 启用 AI 但全局未配 APIKey → nil(不报错降级)。
|
||||
func TestAIReply_NoAPIKeyReturnsNil(t *testing.T) {
|
||||
s, cleanup := newAIStore(t)
|
||||
defer cleanup()
|
||||
ctx := context.Background()
|
||||
s.DB.ExecContext(ctx, `INSERT INTO ai_reply_settings (cookie_id, ai_enabled, custom_prompts) VALUES ('cid', 1, '')`)
|
||||
a := NewAIReplier("cid", s, nil)
|
||||
|
||||
res, err := a.Reply(ctx, chatMsg("在吗", "item1", "chat1"))
|
||||
if err != nil || res != nil {
|
||||
t.Fatalf("无 APIKey 应返回 nil,nil: res=%+v err=%v", res, err)
|
||||
}
|
||||
}
|
||||
|
||||
// mockOpenAIServer 启动一个返回固定 chat completion 响应的 HTTP 服务。
|
||||
// status=0 表示返回成功响应;其余为 HTTP 状态码(用于失败降级测试)。
|
||||
func mockOpenAIServer(t *testing.T, status int, content string) *httptest.Server {
|
||||
t.Helper()
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if status != 0 {
|
||||
http.Error(w, "upstream error", status)
|
||||
return
|
||||
}
|
||||
resp := map[string]any{
|
||||
"choices": []any{map[string]any{
|
||||
"message": map[string]any{"role": "assistant", "content": content},
|
||||
}},
|
||||
}
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
json.NewEncoder(w).Encode(resp)
|
||||
}))
|
||||
t.Cleanup(srv.Close)
|
||||
return srv
|
||||
}
|
||||
|
||||
// TestAIReply_HTTPErrorDegrades AI 调用 HTTP 500 → 返回错误(上层降级到默认回复)。
|
||||
func TestAIReply_HTTPErrorDegrades(t *testing.T) {
|
||||
s, cleanup := newAIStore(t)
|
||||
defer cleanup()
|
||||
ctx := context.Background()
|
||||
srv := mockOpenAIServer(t, http.StatusInternalServerError, "")
|
||||
|
||||
// 启用 AI + 配 APIKey + 指向 mock 服务。
|
||||
s.DB.ExecContext(ctx, `INSERT INTO ai_reply_settings (cookie_id, ai_enabled, custom_prompts) VALUES ('cid', 1, '')`)
|
||||
s.Settings.Set(ctx, "ai_api_key", "sk-test")
|
||||
s.Settings.Set(ctx, "ai_api_url", srv.URL)
|
||||
|
||||
a := NewAIReplier("cid", s, nil)
|
||||
res, err := a.Reply(ctx, chatMsg("在吗", "item1", "chat1"))
|
||||
if err == nil {
|
||||
t.Fatalf("HTTP 500 应返回错误,got res=%+v", res)
|
||||
}
|
||||
if res != nil {
|
||||
t.Fatalf("失败时不应返回结果: %+v", res)
|
||||
}
|
||||
}
|
||||
|
||||
// TestAIReply_EmptyChoicesReturnsNil 成功响应但无 choices → nil(不报错)。
|
||||
func TestAIReply_EmptyChoicesReturnsNil(t *testing.T) {
|
||||
s, cleanup := newAIStore(t)
|
||||
defer cleanup()
|
||||
ctx := context.Background()
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
json.NewEncoder(w).Encode(map[string]any{"choices": []any{}})
|
||||
}))
|
||||
t.Cleanup(srv.Close)
|
||||
s.DB.ExecContext(ctx, `INSERT INTO ai_reply_settings (cookie_id, ai_enabled, custom_prompts) VALUES ('cid', 1, '')`)
|
||||
s.Settings.Set(ctx, "ai_api_key", "sk-test")
|
||||
s.Settings.Set(ctx, "ai_api_url", srv.URL)
|
||||
|
||||
a := NewAIReplier("cid", s, nil)
|
||||
res, err := a.Reply(ctx, chatMsg("在吗", "item1", "chat1"))
|
||||
if err != nil || res != nil {
|
||||
t.Fatalf("空 choices 应返回 nil,nil: res=%+v err=%v", res, err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestAIReply_SuccessReturnsContent 正常调用返回 AI 文本。
|
||||
func TestAIReply_SuccessReturnsContent(t *testing.T) {
|
||||
s, cleanup := newAIStore(t)
|
||||
defer cleanup()
|
||||
ctx := context.Background()
|
||||
srv := mockOpenAIServer(t, 0, "你好,在的哦")
|
||||
s.DB.ExecContext(ctx, `INSERT INTO ai_reply_settings (cookie_id, ai_enabled, custom_prompts) VALUES ('cid', 1, '')`)
|
||||
s.Settings.Set(ctx, "ai_api_key", "sk-test")
|
||||
s.Settings.Set(ctx, "ai_api_url", srv.URL)
|
||||
|
||||
a := NewAIReplier("cid", s, nil)
|
||||
res, err := a.Reply(ctx, chatMsg("在吗", "item1", "chat1"))
|
||||
if err != nil {
|
||||
t.Fatalf("成功调用不应报错: %v", err)
|
||||
}
|
||||
if res == nil || res.Text != "你好,在的哦" {
|
||||
t.Fatalf("应返回 AI 文本: %+v", res)
|
||||
}
|
||||
}
|
||||
|
||||
// TestGlobalAIConfig 默认值兜底 + 显式设置覆盖。
|
||||
func TestGlobalAIConfig(t *testing.T) {
|
||||
s, cleanup := newAIStore(t)
|
||||
defer cleanup()
|
||||
ctx := context.Background()
|
||||
a := NewAIReplier("cid", s, nil)
|
||||
|
||||
// 全空 → 默认 BaseURL + Model。
|
||||
cfg, err := a.globalAIConfig(ctx)
|
||||
if err != nil {
|
||||
t.Fatalf("globalAIConfig: %v", err)
|
||||
}
|
||||
if cfg.BaseURL != defaultAIBaseURL || cfg.Model != defaultAIModel || cfg.APIKey != "" {
|
||||
t.Fatalf("默认值异常: %+v", cfg)
|
||||
}
|
||||
|
||||
// 显式设置。
|
||||
s.Settings.Set(ctx, "ai_api_key", "sk-x")
|
||||
s.Settings.Set(ctx, "ai_api_url", "https://example.com/v1/")
|
||||
s.Settings.Set(ctx, "ai_model", "gpt-4o")
|
||||
cfg, _ = a.globalAIConfig(ctx)
|
||||
if cfg.APIKey != "sk-x" || cfg.BaseURL != "https://example.com/v1" || cfg.Model != "gpt-4o" {
|
||||
t.Fatalf("显式设置异常: %+v", cfg)
|
||||
}
|
||||
}
|
||||
|
||||
// TestAIReplierItemInfo 商品缺失时兜底占位;存在时取真实标题/价格/描述。
|
||||
func TestAIReplierItemInfo(t *testing.T) {
|
||||
s, cleanup := newAIStore(t)
|
||||
defer cleanup()
|
||||
ctx := context.Background()
|
||||
a := NewAIReplier("cid", s, nil)
|
||||
|
||||
// 商品不存在 → 占位。
|
||||
title, price, desc := a.itemInfo(ctx, "no-such-item")
|
||||
if title != "商品信息获取失败" || desc != "暂无商品描述" || price != 0 {
|
||||
t.Fatalf("缺失商品应兜底: title=%q price=%v desc=%q", title, price, desc)
|
||||
}
|
||||
|
||||
// 插入商品。
|
||||
s.DB.ExecContext(ctx, `INSERT INTO item_info (cookie_id, item_id, item_title, item_price, item_detail) VALUES ('cid','item1','会员卡','9.90','月卡服务')`)
|
||||
title, price, desc = a.itemInfo(ctx, "item1")
|
||||
if title != "会员卡" || price != 9.9 || desc != "月卡服务" {
|
||||
t.Fatalf("真实商品: title=%q price=%v desc=%q", title, price, desc)
|
||||
}
|
||||
}
|
||||
@@ -55,20 +55,6 @@ func (a *Account) handleMessage(decrypted map[string]any) {
|
||||
}
|
||||
}
|
||||
|
||||
func (a *Account) cancelDebouncedReply(chatID string) {
|
||||
if chatID == "" {
|
||||
return
|
||||
}
|
||||
a.debounceMu.Lock()
|
||||
defer a.debounceMu.Unlock()
|
||||
if old, ok := a.debounceTimers[chatID]; ok {
|
||||
if old.timer != nil {
|
||||
old.timer.Stop()
|
||||
}
|
||||
delete(a.debounceTimers, chatID)
|
||||
}
|
||||
}
|
||||
|
||||
// markAndCheckDedup 提取消息 ID,检查 1 小时内是否已处理;未处理则标记。
|
||||
// 返回 true 表示应继续处理。移植自 _schedule_debounced_reply 的去重段。
|
||||
func (a *Account) markAndCheckDedup(decrypted map[string]any, chat *ChatMessage) bool {
|
||||
@@ -310,6 +296,8 @@ func contains(s, sub string) bool { return strings.Contains(strings.ToLower(s),
|
||||
|
||||
func toString(v any) string {
|
||||
switch x := v.(type) {
|
||||
case nil:
|
||||
return ""
|
||||
case string:
|
||||
return x
|
||||
case float64:
|
||||
|
||||
@@ -0,0 +1,426 @@
|
||||
package engine
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"xianyu-go/internal/automation"
|
||||
)
|
||||
|
||||
// TestHandleMessage_SystemEventRoutesToAutomation 付款待发货系统卡片进入自动化中心,不进入回复链。
|
||||
func TestHandleMessage_SystemEventRoutesToAutomation(t *testing.T) {
|
||||
acc, h, _, cleanup := newAccountForTest(t)
|
||||
defer cleanup()
|
||||
defer acc.Stop()
|
||||
|
||||
decrypted := mustPaidDeliveryCard(t)
|
||||
acc.handleMessage(decrypted)
|
||||
|
||||
// 系统事件应交给 handler.HandleSystemEvent(recordingHandler 目前不记录系统事件,
|
||||
// 但自动化 ExtractTaskFromWS 应识别为 TriggerOrderPaid——这里通过 handler 间接断言)。
|
||||
// 直接验证:handleMessage 不应触发任何防抖回复投递。
|
||||
time.Sleep(MessageDebounceDelay + 200*time.Millisecond)
|
||||
h.mu.Lock()
|
||||
chats := len(h.chats)
|
||||
h.mu.Unlock()
|
||||
if chats != 0 {
|
||||
t.Errorf("系统卡片不应进入回复链,got %d 条聊天投递", chats)
|
||||
}
|
||||
}
|
||||
|
||||
// systemCapturingHandler 捕获系统事件,用于断言 handleMessage 把系统卡片交给自动化。
|
||||
type systemCapturingHandler struct {
|
||||
recordingHandler
|
||||
mu sync.Mutex
|
||||
tasks []automation.Task
|
||||
}
|
||||
|
||||
func (s *systemCapturingHandler) HandleSystemEvent(_ context.Context, task automation.Task) error {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
s.tasks = append(s.tasks, task)
|
||||
return nil
|
||||
}
|
||||
|
||||
// TestHandleMessage_SystemEventDispatchedToHandler 系统卡片经 handleMessage 进入 handler.HandleSystemEvent。
|
||||
func TestHandleMessage_SystemEventDispatchedToHandler(t *testing.T) {
|
||||
acc, _, _, cleanup := newAccountForTest(t)
|
||||
defer cleanup()
|
||||
defer acc.Stop()
|
||||
|
||||
h := &systemCapturingHandler{}
|
||||
acc.handler = h
|
||||
acc.handleMessage(mustPaidDeliveryCard(t))
|
||||
|
||||
h.mu.Lock()
|
||||
defer h.mu.Unlock()
|
||||
if len(h.tasks) != 1 {
|
||||
t.Fatalf("应投递 1 个系统事件,got %d", len(h.tasks))
|
||||
}
|
||||
if h.tasks[0].TriggerType != automation.TriggerOrderPaid {
|
||||
t.Errorf("TriggerType=%q want %q", h.tasks[0].TriggerType, automation.TriggerOrderPaid)
|
||||
}
|
||||
}
|
||||
|
||||
// TestHandleMessage_PlainChatRoutesToDebounce 普通聊天消息进入防抖回复链。
|
||||
func TestHandleMessage_PlainChatRoutesToDebounce(t *testing.T) {
|
||||
acc, h, _, cleanup := newAccountForTest(t)
|
||||
defer cleanup()
|
||||
defer acc.Stop()
|
||||
|
||||
// 构造一条普通聊天消息(非系统卡片、非 contentType 14/26)。
|
||||
decrypted := plainChatMessage(t, "你好老板", "buyer1", "chat-plain")
|
||||
acc.handleMessage(decrypted)
|
||||
|
||||
time.Sleep(MessageDebounceDelay + 200*time.Millisecond)
|
||||
h.mu.Lock()
|
||||
defer h.mu.Unlock()
|
||||
if len(h.chats) != 1 {
|
||||
t.Fatalf("应投递 1 条聊天消息,got %d", len(h.chats))
|
||||
}
|
||||
if h.chats[0].Text != "你好老板" {
|
||||
t.Errorf("Text=%q want 你好老板", h.chats[0].Text)
|
||||
}
|
||||
}
|
||||
|
||||
// TestHandleMessage_ContentType14Filtered contentType=14 系统提示不进入回复链。
|
||||
func TestHandleMessage_ContentType14Filtered(t *testing.T) {
|
||||
acc, h, _, cleanup := newAccountForTest(t)
|
||||
defer cleanup()
|
||||
defer acc.Stop()
|
||||
|
||||
acc.handleMessage(mustContentType14Notice(t))
|
||||
time.Sleep(MessageDebounceDelay + 200*time.Millisecond)
|
||||
h.mu.Lock()
|
||||
defer h.mu.Unlock()
|
||||
if len(h.chats) != 0 {
|
||||
t.Errorf("contentType=14 不应进入回复链,got %d", len(h.chats))
|
||||
}
|
||||
}
|
||||
|
||||
// TestHandleMessage_RefundCardFiltered contentType=26 退款卡片不进入回复链。
|
||||
func TestHandleMessage_RefundCardFiltered(t *testing.T) {
|
||||
acc, h, _, cleanup := newAccountForTest(t)
|
||||
defer cleanup()
|
||||
defer acc.Stop()
|
||||
|
||||
acc.handleMessage(mustRefundTradeCard(t))
|
||||
time.Sleep(MessageDebounceDelay + 200*time.Millisecond)
|
||||
h.mu.Lock()
|
||||
defer h.mu.Unlock()
|
||||
if len(h.chats) != 0 {
|
||||
t.Errorf("退款卡片不应进入回复链,got %d", len(h.chats))
|
||||
}
|
||||
}
|
||||
|
||||
// TestHandleMessage_DedupSkipsRepeat 同一 msgID 的重复消息只处理一次。
|
||||
func TestHandleMessage_DedupSkipsRepeat(t *testing.T) {
|
||||
acc, h, _, cleanup := newAccountForTest(t)
|
||||
defer cleanup()
|
||||
defer acc.Stop()
|
||||
|
||||
decrypted := plainChatMessage(t, "重复消息", "buyer1", "chat-dup")
|
||||
acc.handleMessage(decrypted)
|
||||
acc.handleMessage(decrypted) // 重复
|
||||
acc.handleMessage(decrypted) // 再次重复
|
||||
|
||||
time.Sleep(MessageDebounceDelay + 200*time.Millisecond)
|
||||
h.mu.Lock()
|
||||
defer h.mu.Unlock()
|
||||
if len(h.chats) != 1 {
|
||||
t.Errorf("去重后应只投递 1 条,got %d", len(h.chats))
|
||||
}
|
||||
}
|
||||
|
||||
// TestHandleMessage_NoReminderNoOp 无 reminderContent 的消息不进入回复链也不报错。
|
||||
func TestHandleMessage_NoReminderNoOp(t *testing.T) {
|
||||
acc, h, _, cleanup := newAccountForTest(t)
|
||||
defer cleanup()
|
||||
defer acc.Stop()
|
||||
|
||||
// 缺少 reminderContent 的消息。
|
||||
decrypted := map[string]any{
|
||||
"1": map[string]any{
|
||||
"2": "123@goofish",
|
||||
"10": map[string]any{
|
||||
"senderUserId": "b1",
|
||||
},
|
||||
},
|
||||
}
|
||||
acc.handleMessage(decrypted)
|
||||
time.Sleep(MessageDebounceDelay + 200*time.Millisecond)
|
||||
h.mu.Lock()
|
||||
defer h.mu.Unlock()
|
||||
if len(h.chats) != 0 {
|
||||
t.Errorf("无 reminder 不应投递,got %d", len(h.chats))
|
||||
}
|
||||
}
|
||||
|
||||
// TestDispatch_UpdatesLastMsgReceived dispatch 记录消息接收时间。
|
||||
func TestDispatch_UpdatesLastMsgReceived(t *testing.T) {
|
||||
acc, _, _, cleanup := newAccountForTest(t)
|
||||
defer cleanup()
|
||||
defer acc.Stop()
|
||||
|
||||
acc.mu.Lock()
|
||||
acc.lastMsgReceived = time.Time{}
|
||||
acc.mu.Unlock()
|
||||
|
||||
before := time.Now()
|
||||
acc.dispatch(plainChatMessage(t, "hi", "b1", "c1"))
|
||||
// dispatch 内部起 goroutine,等其更新 lastMsgReceived。
|
||||
time.Sleep(50 * time.Millisecond)
|
||||
|
||||
acc.mu.Lock()
|
||||
last := acc.lastMsgReceived
|
||||
acc.mu.Unlock()
|
||||
if last.IsZero() || last.Before(before) {
|
||||
t.Errorf("dispatch 应更新 lastMsgReceived,got %v", last)
|
||||
}
|
||||
}
|
||||
|
||||
// TestDispatch_SemaphoreOverflowDrops 消息并发达上限时丢弃多余消息(不阻塞)。
|
||||
func TestDispatch_SemaphoreOverflowDrops(t *testing.T) {
|
||||
acc, _, _, cleanup := newAccountForTest(t)
|
||||
defer cleanup()
|
||||
defer acc.Stop()
|
||||
|
||||
// 把信号量填满,再投递一条:应走 default 分支丢弃,不阻塞。
|
||||
for i := 0; i < MessageSemaphoreSize; i++ {
|
||||
acc.sem <- struct{}{}
|
||||
}
|
||||
// 这条应被丢弃(dispatch 立即返回,不进入 handleMessage)。
|
||||
done := make(chan struct{})
|
||||
go func() {
|
||||
acc.dispatch(plainChatMessage(t, "overflow", "b1", "c1"))
|
||||
close(done)
|
||||
}()
|
||||
select {
|
||||
case <-done:
|
||||
case <-time.After(time.Second):
|
||||
t.Fatal("dispatch 在信号量满时应立即返回,不应阻塞")
|
||||
}
|
||||
|
||||
// 释放信号量,避免 Stop 时泄漏 goroutine。
|
||||
for i := 0; i < MessageSemaphoreSize; i++ {
|
||||
<-acc.sem
|
||||
}
|
||||
}
|
||||
|
||||
// TestScheduleDebouncedReply_DifferentChatIDsNotCoalesced 不同 chat_id 的消息各自独立防抖,不合并。
|
||||
func TestScheduleDebouncedReply_DifferentChatIDsNotCoalesced(t *testing.T) {
|
||||
acc, h, _, cleanup := newAccountForTest(t)
|
||||
defer cleanup()
|
||||
defer acc.Stop()
|
||||
|
||||
chat1 := ChatMessage{AccountID: "cid", ChatID: "chat-a", Text: "A1", SenderUserID: "b1"}
|
||||
chat2 := ChatMessage{AccountID: "cid", ChatID: "chat-b", Text: "B1", SenderUserID: "b2"}
|
||||
chat1.CookieStr = "cookie"
|
||||
chat2.CookieStr = "cookie"
|
||||
|
||||
acc.scheduleDebouncedReply(chat1)
|
||||
acc.scheduleDebouncedReply(chat2)
|
||||
|
||||
time.Sleep(MessageDebounceDelay + 200*time.Millisecond)
|
||||
h.mu.Lock()
|
||||
defer h.mu.Unlock()
|
||||
if len(h.chats) != 2 {
|
||||
t.Fatalf("不同 chat_id 应各自投递,got %d 条: %+v", len(h.chats), h.chats)
|
||||
}
|
||||
texts := map[string]bool{}
|
||||
for _, c := range h.chats {
|
||||
texts[c.Text] = true
|
||||
}
|
||||
if !texts["A1"] || !texts["B1"] {
|
||||
t.Errorf("应投递 A1 和 B1,got %+v", texts)
|
||||
}
|
||||
}
|
||||
|
||||
// TestScheduleDebouncedReply_TimerReset 同一 chat_id 连续消息重置定时器,旧消息被跳过。
|
||||
func TestScheduleDebouncedReply_TimerReset(t *testing.T) {
|
||||
acc, h, _, cleanup := newAccountForTest(t)
|
||||
defer cleanup()
|
||||
defer acc.Stop()
|
||||
|
||||
// 第一条立即调度。
|
||||
first := ChatMessage{AccountID: "cid", ChatID: "chat-reset", Text: "first", SenderUserID: "b1"}
|
||||
first.CookieStr = "cookie"
|
||||
acc.scheduleDebouncedReply(first)
|
||||
|
||||
// 在防抖延迟内再投递第二条,应取消第一条的定时器。
|
||||
time.Sleep(MessageDebounceDelay / 2)
|
||||
second := ChatMessage{AccountID: "cid", ChatID: "chat-reset", Text: "second", SenderUserID: "b1"}
|
||||
second.CookieStr = "cookie"
|
||||
acc.scheduleDebouncedReply(second)
|
||||
|
||||
time.Sleep(MessageDebounceDelay + 300*time.Millisecond)
|
||||
h.mu.Lock()
|
||||
defer h.mu.Unlock()
|
||||
if len(h.chats) != 1 {
|
||||
t.Fatalf("应只投递最后一条,got %d: %+v", len(h.chats), h.chats)
|
||||
}
|
||||
if h.chats[0].Text != "second" {
|
||||
t.Errorf("应投递 second,got %q", h.chats[0].Text)
|
||||
}
|
||||
}
|
||||
|
||||
// TestScheduleDebouncedReply_StopClearsTimers Stop 后未触发的定时器被取消,不再投递。
|
||||
func TestScheduleDebouncedReply_StopClearsTimers(t *testing.T) {
|
||||
acc, h, _, cleanup := newAccountForTest(t)
|
||||
defer cleanup()
|
||||
|
||||
chat := ChatMessage{AccountID: "cid", ChatID: "chat-stop", Text: "won't deliver", SenderUserID: "b1"}
|
||||
chat.CookieStr = "cookie"
|
||||
acc.scheduleDebouncedReply(chat)
|
||||
// 立即 Stop,定时器应被取消。
|
||||
acc.Stop()
|
||||
|
||||
time.Sleep(MessageDebounceDelay + 200*time.Millisecond)
|
||||
h.mu.Lock()
|
||||
defer h.mu.Unlock()
|
||||
if len(h.chats) != 0 {
|
||||
t.Errorf("Stop 后定时器应被取消,不应投递,got %d", len(h.chats))
|
||||
}
|
||||
}
|
||||
|
||||
// TestCleanupDedupLocked_ExpiredRemoved 过期消息 ID 被清理。
|
||||
func TestCleanupDedupLocked_ExpiredRemoved(t *testing.T) {
|
||||
acc, _, _, cleanup := newAccountForTest(t)
|
||||
defer cleanup()
|
||||
defer acc.Stop()
|
||||
|
||||
now := time.Now()
|
||||
acc.dedupMu.Lock()
|
||||
// 一条过期(>1h)、一条新鲜。
|
||||
acc.processed["old-msg"] = now.Add(-2 * time.Hour)
|
||||
acc.processed["fresh-msg"] = now
|
||||
acc.dedupMu.Unlock()
|
||||
|
||||
acc.dedupMu.Lock()
|
||||
acc.cleanupDedupLocked(now)
|
||||
acc.dedupMu.Unlock()
|
||||
|
||||
acc.dedupMu.Lock()
|
||||
defer acc.dedupMu.Unlock()
|
||||
if _, ok := acc.processed["old-msg"]; ok {
|
||||
t.Error("过期消息应被清理")
|
||||
}
|
||||
if _, ok := acc.processed["fresh-msg"]; !ok {
|
||||
t.Error("新鲜消息不应被清理")
|
||||
}
|
||||
}
|
||||
|
||||
// TestCleanupDedupLocked_OverLimitDropsOldestHalf 超上限且都未过期时删最旧一半。
|
||||
func TestCleanupDedupLocked_OverLimitDropsOldestHalf(t *testing.T) {
|
||||
acc, _, _, cleanup := newAccountForTest(t)
|
||||
defer cleanup()
|
||||
defer acc.Stop()
|
||||
|
||||
now := time.Now()
|
||||
acc.dedupMu.Lock()
|
||||
// 填入 ProcessedIDsMaxSize + 10 条新鲜消息,时间递增。
|
||||
total := ProcessedIDsMaxSize + 10
|
||||
for i := 0; i < total; i++ {
|
||||
// 时间按 i 递增,确保有明确的最旧一半。
|
||||
acc.processed["msg-"+itoa(i)] = now.Add(time.Duration(i) * time.Millisecond)
|
||||
}
|
||||
acc.cleanupDedupLocked(now)
|
||||
remaining := len(acc.processed)
|
||||
acc.dedupMu.Unlock()
|
||||
|
||||
// 删最旧一半后:total - total/2 = (ProcessedIDsMaxSize+10) - (ProcessedIDsMaxSize+10)/2。
|
||||
want := total - total/2
|
||||
if remaining != want {
|
||||
t.Errorf("超上限删半后剩余 %d,want %d", remaining, want)
|
||||
}
|
||||
}
|
||||
|
||||
// itoa 简单整数转字符串,避免引入 strconv。
|
||||
func itoa(n int) string {
|
||||
if n == 0 {
|
||||
return "0"
|
||||
}
|
||||
neg := n < 0
|
||||
if neg {
|
||||
n = -n
|
||||
}
|
||||
var b [20]byte
|
||||
i := len(b)
|
||||
for n > 0 {
|
||||
i--
|
||||
b[i] = byte('0' + n%10)
|
||||
n /= 10
|
||||
}
|
||||
if neg {
|
||||
i--
|
||||
b[i] = '-'
|
||||
}
|
||||
return string(b[i:])
|
||||
}
|
||||
|
||||
// TestCleanupDedupLocked_TriggeredByMarkAndCheck markAndCheckDedup 在超上限时触发清理。
|
||||
func TestCleanupDedupLocked_TriggeredByMarkAndCheck(t *testing.T) {
|
||||
acc, _, _, cleanup := newAccountForTest(t)
|
||||
defer cleanup()
|
||||
defer acc.Stop()
|
||||
|
||||
now := time.Now()
|
||||
acc.dedupMu.Lock()
|
||||
// 预填 ProcessedIDsMaxSize 条过期消息,使下一次 markAndCheckDedup 触发清理。
|
||||
for i := 0; i < ProcessedIDsMaxSize; i++ {
|
||||
acc.processed["old-"+itoa(i)] = now.Add(-2 * time.Hour)
|
||||
}
|
||||
acc.dedupMu.Unlock()
|
||||
|
||||
// 构造一条新消息触发清理。msgID 由 extractMessageID 提取,这里直接用现成样本。
|
||||
decrypted := plainChatMessage(t, "trigger", "b1", "c1")
|
||||
chat := extractChatMessage(decrypted, "cid", "cookie")
|
||||
if !acc.markAndCheckDedup(decrypted, chat) {
|
||||
t.Fatal("新消息应允许处理")
|
||||
}
|
||||
|
||||
acc.dedupMu.Lock()
|
||||
remaining := len(acc.processed)
|
||||
acc.dedupMu.Unlock()
|
||||
// 过期消息应被清理,仅剩新消息 1 条(或新消息+残留,但应远小于 ProcessedIDsMaxSize)。
|
||||
if remaining >= ProcessedIDsMaxSize {
|
||||
t.Errorf("清理应大幅缩减 processed,剩 %d", remaining)
|
||||
}
|
||||
}
|
||||
|
||||
// TestScheduleDebouncedReply_HandlerErrorLogged reply.Handle 报错仅记录日志,不影响 handler 投递。
|
||||
func TestScheduleDebouncedReply_HandlerErrorLogged(t *testing.T) {
|
||||
acc, h, store, cleanup := newAccountForTest(t)
|
||||
defer cleanup()
|
||||
defer acc.Stop()
|
||||
|
||||
// 让 reply.Handle 走默认回复路径并成功发送(sender 是 acc 自身,无 conn 会失败但仅记录日志)。
|
||||
// 这里主要验证防抖回调路径在 reply 报错时仍会调用 handler.HandleChatMessage。
|
||||
_ = store
|
||||
chat := ChatMessage{
|
||||
AccountID: "cid", ChatID: "chat-err", Text: "hi",
|
||||
SenderUserID: "b1", CookieStr: "unb=123;",
|
||||
}
|
||||
acc.scheduleDebouncedReply(chat)
|
||||
time.Sleep(MessageDebounceDelay + 200*time.Millisecond)
|
||||
h.mu.Lock()
|
||||
defer h.mu.Unlock()
|
||||
if len(h.chats) != 1 {
|
||||
t.Errorf("应投递到 handler,got %d", len(h.chats))
|
||||
}
|
||||
}
|
||||
|
||||
// plainChatMessage 构造一条普通聊天消息(非系统卡片、contentType 非 14/26),
|
||||
// 含 bizTag.messageId 以便去重提取。
|
||||
func plainChatMessage(t *testing.T, text, senderUserID, chatID string) map[string]any {
|
||||
t.Helper()
|
||||
s := `{"1":{"2":"` + chatID + `@goofish","10":{"bizTag":"{\"messageId\":\"msg-` + chatID + `\"}","reminderContent":"` + text + `","senderUserId":"` + senderUserID + `","senderNick":"买家","reminderUrl":"fleamarket://message_chat?itemId=item-` + chatID + `&peerUserId=` + senderUserID + `"}}}`
|
||||
var m map[string]any
|
||||
if err := json.Unmarshal([]byte(s), &m); err != nil {
|
||||
t.Fatalf("unmarshal: %v", err)
|
||||
}
|
||||
return m
|
||||
}
|
||||
@@ -0,0 +1,148 @@
|
||||
package engine
|
||||
|
||||
import (
|
||||
"context"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"xianyu-go/internal/xianyu/mtop"
|
||||
)
|
||||
|
||||
// countingMtop 包装 fakeRunMtop,计数 RefreshToken 调用次数。
|
||||
type countingMtop struct {
|
||||
fakeRunMtop
|
||||
calls int32
|
||||
}
|
||||
|
||||
func (c *countingMtop) RefreshTokenWithDeviceIDContext(_ context.Context, _ string, _ string) (*mtop.RefreshResult, error) {
|
||||
atomic.AddInt32(&c.calls, 1)
|
||||
return &mtop.RefreshResult{AccessToken: c.token}, nil
|
||||
}
|
||||
|
||||
// TestAcquireToken_CacheHitSkipsMtop 缓存命中且未过期时跳过 mtop 调用。
|
||||
func TestAcquireToken_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)
|
||||
}
|
||||
token, _, err := acc.acquireToken(context.Background())
|
||||
if err != nil {
|
||||
t.Fatalf("acquireToken: %v", err)
|
||||
}
|
||||
if token != "cached-tok" {
|
||||
t.Fatalf("应使用缓存 token,got %s", token)
|
||||
}
|
||||
if calls := atomic.LoadInt32(&mtopClient.calls); calls != 0 {
|
||||
t.Fatalf("缓存命中不应调用 mtop,got %d", calls)
|
||||
}
|
||||
}
|
||||
|
||||
// TestAcquireToken_CacheMissCallsMtopAndSavesCache 缓存未命中时调 mtop 并把结果落库。
|
||||
func TestAcquireToken_CacheMissCallsMtopAndSavesCache(t *testing.T) {
|
||||
mtopClient := &countingMtop{fakeRunMtop: fakeRunMtop{token: "tok-mtop"}}
|
||||
acc, _, store, cleanup := newRunAccount(t, mtopClient)
|
||||
defer cleanup()
|
||||
|
||||
token, _, err := acc.acquireToken(context.Background())
|
||||
if err != nil {
|
||||
t.Fatalf("acquireToken: %v", err)
|
||||
}
|
||||
if token != "tok-mtop" {
|
||||
t.Fatalf("应使用 mtop token,got %s", token)
|
||||
}
|
||||
if calls := atomic.LoadInt32(&mtopClient.calls); calls != 1 {
|
||||
t.Fatalf("缓存未命中应调一次 mtop,got %d", calls)
|
||||
}
|
||||
tk, err := store.Tokens.Get(context.Background(), "cid")
|
||||
if err != nil {
|
||||
t.Fatalf("缓存应已落库: %v", err)
|
||||
}
|
||||
if tk.AccessToken != "tok-mtop" {
|
||||
t.Fatalf("缓存 token 应为 tok-mtop,got %s", tk.AccessToken)
|
||||
}
|
||||
if tk.ExpireAt <= time.Now().Unix() {
|
||||
t.Fatalf("缓存 expire_at 应在未来,got %d", tk.ExpireAt)
|
||||
}
|
||||
}
|
||||
|
||||
// TestReloadCookieFromDB_AdoptsNewCookieAndClearsCache DB cookie 变更时采纳新 cookie 并清旧 token 缓存。
|
||||
func TestReloadCookieFromDB_AdoptsNewCookieAndClearsCache(t *testing.T) {
|
||||
acc, _, store, cleanup := newRunAccount(t, &fakeRunMtop{token: "tok-1"})
|
||||
defer cleanup()
|
||||
// 预置旧 session 的 token 缓存。
|
||||
if err := store.Tokens.Save(context.Background(), "cid", acc.deviceID, "old-tok",
|
||||
time.Now().Add(time.Hour).Unix()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// 外部更新 DB cookie(模拟重新扫码),userID=0 复用现有 user_id。
|
||||
newCookie := "unb=123; _m_h5_tk=newtk_2; sgcookie=abc"
|
||||
if err := store.Cookies.Save(context.Background(), "cid", newCookie, 0); err != nil {
|
||||
t.Fatalf("Save: %v", err)
|
||||
}
|
||||
acc.reloadCookieFromDB(context.Background())
|
||||
if acc.CookieStr != newCookie {
|
||||
t.Fatalf("应采纳 DB 新 cookie,got %s", acc.CookieStr)
|
||||
}
|
||||
// 新 cookie 对应新 session,旧 token 缓存应被清除。
|
||||
if _, err := store.Tokens.Get(context.Background(), "cid"); err == nil {
|
||||
t.Fatal("cookie 变更后应清除 token 缓存")
|
||||
}
|
||||
}
|
||||
|
||||
// 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 慢重试路径只告警一次。
|
||||
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)
|
||||
}
|
||||
call()
|
||||
call()
|
||||
if len(h.alerts) != 1 || h.alerts[0] != AlertLevelCritical {
|
||||
t.Fatalf("两次 handleMaxFailures 应只告警一次,got %+v", h.alerts)
|
||||
}
|
||||
}
|
||||
@@ -8,7 +8,6 @@ package engine
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"strings"
|
||||
|
||||
@@ -184,7 +183,9 @@ func (r *ReplyService) defaultReply(ctx context.Context, m ChatMessage) *ReplyRe
|
||||
}
|
||||
// 记录已回复。
|
||||
if dr.ReplyOnce && m.ChatID != "" {
|
||||
_ = r.store.DefaultReps.AddRecord(ctx, r.cookieID, m.ChatID)
|
||||
if err := r.store.DefaultReps.AddRecord(ctx, r.cookieID, m.ChatID); err != nil {
|
||||
r.logger.Error("记录默认回复失败", "cookie_id", r.cookieID, "chat_id", m.ChatID, "err", err)
|
||||
}
|
||||
}
|
||||
res := &ReplyResult{Source: "默认"}
|
||||
if strings.TrimSpace(dr.ReplyContent) != "" {
|
||||
@@ -224,6 +225,3 @@ func safeFormat(template string, vars map[string]string) string {
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// 占位防未用 fmt(未来错误信息用)。
|
||||
var _ = fmt.Sprintf
|
||||
@@ -0,0 +1,273 @@
|
||||
package engine
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"testing"
|
||||
|
||||
"xianyu-go/internal/db"
|
||||
)
|
||||
|
||||
// fakeAPIReplier 可控的 API 回复 mock:返回预设结果或错误。
|
||||
type fakeAPIReplier struct {
|
||||
result *ReplyResult
|
||||
err error
|
||||
called int
|
||||
}
|
||||
|
||||
func (f *fakeAPIReplier) Reply(_ context.Context, _ ChatMessage) (*ReplyResult, error) {
|
||||
f.called++
|
||||
return f.result, f.err
|
||||
}
|
||||
|
||||
// fakeAIReplier 可控的 AI 回复 mock。
|
||||
type fakeAIReplier struct {
|
||||
result *ReplyResult
|
||||
err error
|
||||
called int
|
||||
}
|
||||
|
||||
func (f *fakeAIReplier) Reply(_ context.Context, _ ChatMessage) (*ReplyResult, error) {
|
||||
f.called++
|
||||
return f.result, f.err
|
||||
}
|
||||
|
||||
// recordingSender 记录发送的文本/图片,用于断言回复投递。
|
||||
type recordingSender struct {
|
||||
texts []textSent
|
||||
images []imageSent
|
||||
}
|
||||
|
||||
type textSent struct {
|
||||
chatID, toUserID, text string
|
||||
}
|
||||
|
||||
type imageSent struct {
|
||||
chatID, toUserID, url string
|
||||
cardID int64
|
||||
}
|
||||
|
||||
func (r *recordingSender) SendText(_ context.Context, chatID, toUserID, text string) error {
|
||||
r.texts = append(r.texts, textSent{chatID, toUserID, text})
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *recordingSender) SendImage(_ context.Context, chatID, toUserID, url string, cardID int64) error {
|
||||
r.images = append(r.images, imageSent{chatID, toUserID, url, cardID})
|
||||
return nil
|
||||
}
|
||||
|
||||
// TestReply_APIPriorityAndError API 回复命中时优先级最高;API 报错时降级到关键词。
|
||||
func TestReply_APIPriorityAndError(t *testing.T) {
|
||||
s, cleanup := newReplyStore(t)
|
||||
defer cleanup()
|
||||
ctx := context.Background()
|
||||
s.DB.ExecContext(ctx, `INSERT INTO keywords (cookie_id,keyword,reply,type) VALUES ('cid','在吗','关键词回复','text')`)
|
||||
|
||||
// API 返回结果 → 用 API。
|
||||
api := &fakeAPIReplier{result: &ReplyResult{Text: "API回复"}}
|
||||
r := NewReplyService("cid", s, nil, api, nil, nil)
|
||||
res := r.resolve(ctx, chatMsg("在吗", "", "chat1"))
|
||||
if res == nil || res.Source != "API" || res.Text != "API回复" {
|
||||
t.Fatalf("API 命中应优先,got %+v", res)
|
||||
}
|
||||
|
||||
// API 报错 → 降级到关键词。
|
||||
api2 := &fakeAPIReplier{err: errors.New("upstream down")}
|
||||
r2 := NewReplyService("cid", s, nil, api2, nil, nil)
|
||||
res2 := r2.resolve(ctx, chatMsg("在吗", "", "chat1"))
|
||||
if res2 == nil || res2.Source != "关键词" || res2.Text != "关键词回复" {
|
||||
t.Fatalf("API 报错应降级到关键词,got %+v", res2)
|
||||
}
|
||||
|
||||
// API 返回 nil(无回复)→ 降级到关键词。
|
||||
api3 := &fakeAPIReplier{result: nil}
|
||||
r3 := NewReplyService("cid", s, nil, api3, nil, nil)
|
||||
res3 := r3.resolve(ctx, chatMsg("在吗", "", "chat1"))
|
||||
if res3 == nil || res3.Source != "关键词" {
|
||||
t.Fatalf("API nil 应降级到关键词,got %+v", res3)
|
||||
}
|
||||
}
|
||||
|
||||
// TestReply_AIPriorityOverDefault AI 回复优先于默认回复;AI 报错降级到默认。
|
||||
func TestReply_AIPriorityOverDefault(t *testing.T) {
|
||||
s, cleanup := newReplyStore(t)
|
||||
defer cleanup()
|
||||
ctx := context.Background()
|
||||
s.DB.ExecContext(ctx, `INSERT INTO default_replies (cookie_id,enabled,reply_content,reply_once) VALUES ('cid',1,'默认回复',0)`)
|
||||
|
||||
ai := &fakeAIReplier{result: &ReplyResult{Text: "AI回复"}}
|
||||
r := NewReplyService("cid", s, nil, nil, ai, nil)
|
||||
res := r.resolve(ctx, chatMsg("复杂问题", "", "chat1"))
|
||||
if res == nil || res.Source != "AI" || res.Text != "AI回复" {
|
||||
t.Fatalf("AI 命中应优先于默认,got %+v", res)
|
||||
}
|
||||
|
||||
// AI 报错 → 降级到默认。
|
||||
ai2 := &fakeAIReplier{err: errors.New("model timeout")}
|
||||
r2 := NewReplyService("cid", s, nil, nil, ai2, nil)
|
||||
res2 := r2.resolve(ctx, chatMsg("复杂问题", "", "chat1"))
|
||||
if res2 == nil || res2.Source != "默认" || res2.Text != "默认回复" {
|
||||
t.Fatalf("AI 报错应降级到默认,got %+v", res2)
|
||||
}
|
||||
}
|
||||
|
||||
// TestReply_ImageKeyword 图片类型关键词返回 ImageURL。
|
||||
func TestReply_ImageKeyword(t *testing.T) {
|
||||
s, cleanup := newReplyStore(t)
|
||||
defer cleanup()
|
||||
ctx := context.Background()
|
||||
s.DB.ExecContext(ctx, `INSERT INTO keywords (cookie_id,keyword,reply,image_url,type) VALUES ('cid','看图','','http://img/x.png','image')`)
|
||||
|
||||
r := NewReplyService("cid", s, nil, nil, nil, nil)
|
||||
res := r.resolve(ctx, chatMsg("发看图", "item1", "chat1"))
|
||||
if res == nil || res.Source != "关键词" || res.ImageURL != "http://img/x.png" {
|
||||
t.Fatalf("图片关键词应返回 ImageURL,got %+v", res)
|
||||
}
|
||||
}
|
||||
|
||||
// TestReply_HandleSendsImageThenText Handle 先发图片后发文本;Skip 不发送。
|
||||
func TestReply_HandleSendsImageThenText(t *testing.T) {
|
||||
s, cleanup := newReplyStore(t)
|
||||
defer cleanup()
|
||||
ctx := context.Background()
|
||||
s.DB.ExecContext(ctx, `INSERT INTO default_replies (cookie_id,enabled,reply_content,reply_image_url,reply_once) VALUES ('cid',1,'文字','http://img/y.png',0)`)
|
||||
|
||||
sender := &recordingSender{}
|
||||
r := NewReplyService("cid", s, sender, nil, nil, nil)
|
||||
if err := r.Handle(ctx, chatMsg("在吗", "", "chat9")); err != nil {
|
||||
t.Fatalf("Handle: %v", err)
|
||||
}
|
||||
if len(sender.images) != 1 || sender.images[0].url != "http://img/y.png" {
|
||||
t.Fatalf("应先发图片,got %+v", sender.images)
|
||||
}
|
||||
if len(sender.texts) != 1 || sender.texts[0].text != "文字" {
|
||||
t.Fatalf("再发文本,got %+v", sender.texts)
|
||||
}
|
||||
|
||||
// Skip(空默认回复)不应发送任何内容。
|
||||
s.DB.ExecContext(ctx, `UPDATE default_replies SET reply_content='', reply_image_url='' WHERE cookie_id='cid'`)
|
||||
sender2 := &recordingSender{}
|
||||
r2 := NewReplyService("cid", s, sender2, nil, nil, nil)
|
||||
if err := r2.Handle(ctx, chatMsg("在吗", "", "chat9")); err != nil {
|
||||
t.Fatalf("Handle skip: %v", err)
|
||||
}
|
||||
if len(sender2.texts) != 0 || len(sender2.images) != 0 {
|
||||
t.Fatalf("Skip 不应发送,got texts=%+v images=%+v", sender2.texts, sender2.images)
|
||||
}
|
||||
}
|
||||
|
||||
// TestParseMessageIDFromJSON bizTag/extJson 中提取 messageId。
|
||||
func TestParseMessageIDFromJSON(t *testing.T) {
|
||||
cases := map[string]string{
|
||||
`{"messageId":"abc123"}`: "abc123",
|
||||
`{"sourceId":"x"}`: "",
|
||||
`not json`: "",
|
||||
`{}`: "",
|
||||
}
|
||||
for in, want := range cases {
|
||||
if got := parseMessageIDFromJSON(in); got != want {
|
||||
t.Errorf("parseMessageIDFromJSON(%q)=%q want %q", in, got, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestExtractMessageID 优先 bizTag,其次 extJson,无则空。
|
||||
func TestExtractMessageID(t *testing.T) {
|
||||
if got := extractMessageID(map[string]any{
|
||||
"1": map[string]any{
|
||||
"10": map[string]any{
|
||||
"bizTag": `{"messageId":"biz-id"}`,
|
||||
"extJson": `{"messageId":"ext-id"}`,
|
||||
},
|
||||
},
|
||||
}); got != "biz-id" {
|
||||
t.Errorf("bizTag 优先: got %q", got)
|
||||
}
|
||||
if got := extractMessageID(map[string]any{
|
||||
"1": map[string]any{
|
||||
"10": map[string]any{
|
||||
"extJson": `{"messageId":"ext-id"}`,
|
||||
},
|
||||
},
|
||||
}); got != "ext-id" {
|
||||
t.Errorf("extJson 兜底: got %q", got)
|
||||
}
|
||||
if got := extractMessageID(map[string]any{"1": map[string]any{}}); got != "" {
|
||||
t.Errorf("无 ID: got %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
// TestMessageContentType extJson 优先,其次 m6.3.4,再其次 m6.3.5 内嵌 JSON。
|
||||
func TestMessageContentType(t *testing.T) {
|
||||
// extJson 命中。
|
||||
if got := messageContentType(
|
||||
map[string]any{},
|
||||
map[string]any{"extJson": `{"contentType":"14"}`},
|
||||
); got != "14" {
|
||||
t.Errorf("extJson: got %q", got)
|
||||
}
|
||||
// m6.3.4 数字字段(toString 把 float64 转 "26")。
|
||||
if got := messageContentType(
|
||||
map[string]any{"6": map[string]any{"3": map[string]any{"4": float64(26)}}},
|
||||
map[string]any{},
|
||||
); got != "26" {
|
||||
t.Errorf("m6.3.4: got %q", got)
|
||||
}
|
||||
// m6.3.5 内嵌 JSON。
|
||||
if got := messageContentType(
|
||||
map[string]any{"6": map[string]any{"3": map[string]any{"5": `{"contentType":"14"}`}}},
|
||||
map[string]any{},
|
||||
); got != "14" {
|
||||
t.Errorf("m6.3.5: got %q", got)
|
||||
}
|
||||
// 都没有 → 空。
|
||||
if got := messageContentType(map[string]any{}, map[string]any{}); got != "" {
|
||||
t.Errorf("空: got %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
// TestIsNonUserChatNotice contentType 14/26 为系统提示,应过滤。
|
||||
func TestIsNonUserChatNotice(t *testing.T) {
|
||||
if !isNonUserChatNotice(map[string]any{}, map[string]any{"extJson": `{"contentType":"14"}`}, "[提示]") {
|
||||
t.Error("contentType=14 应判为系统提示")
|
||||
}
|
||||
if !isNonUserChatNotice(map[string]any{}, map[string]any{"extJson": `{"contentType":"26"}`}, "[卡片]") {
|
||||
t.Error("contentType=26 应判为系统提示")
|
||||
}
|
||||
if isNonUserChatNotice(map[string]any{}, map[string]any{}, "[买家说你好]") {
|
||||
t.Error("普通消息不应判为系统提示")
|
||||
}
|
||||
}
|
||||
|
||||
// TestToStringAndTrimFloatInt 数字/字符串安全转换。
|
||||
func TestToStringAndTrimFloatInt(t *testing.T) {
|
||||
if got := toString(float64(26)); got != "26" {
|
||||
t.Errorf("toString(float64 26)=%q", got)
|
||||
}
|
||||
if got := toString("hello"); got != "hello" {
|
||||
t.Errorf("toString(string)=%q", got)
|
||||
}
|
||||
if got := toString(nil); got != "" {
|
||||
t.Errorf("toString(nil)=%q", got)
|
||||
}
|
||||
if got := trimFloatInt(12.00); got != "12" {
|
||||
t.Errorf("trimFloatInt(12.00)=%q", got)
|
||||
}
|
||||
if got := trimFloatInt(12.50); got != "12.5" {
|
||||
t.Errorf("trimFloatInt(12.50)=%q", got)
|
||||
}
|
||||
}
|
||||
|
||||
// TestContains 大小写不敏感包含。
|
||||
func TestContains(t *testing.T) {
|
||||
if !contains("Hello World", "world") {
|
||||
t.Error("应大小写不敏感命中")
|
||||
}
|
||||
if contains("Hello", "xyz") {
|
||||
t.Error("不应误命中")
|
||||
}
|
||||
}
|
||||
|
||||
// 编译期保证 db 包被引用(测试构造 store 时使用)。
|
||||
var _ = db.DialectSQLite
|
||||
@@ -0,0 +1,337 @@
|
||||
package engine
|
||||
|
||||
import (
|
||||
"context"
|
||||
"log/slog"
|
||||
"path/filepath"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"xianyu-go/internal/db"
|
||||
"xianyu-go/internal/xianyu/mtop"
|
||||
"xianyu-go/internal/xianyu/ws"
|
||||
)
|
||||
|
||||
// fakeRunMtop 返回成功 token,不触网。
|
||||
type fakeRunMtop struct{ token string }
|
||||
|
||||
func (f *fakeRunMtop) FetchUserProfile(context.Context, string) (*mtop.UserProfileResult, error) {
|
||||
return nil, nil
|
||||
}
|
||||
func (f *fakeRunMtop) ConsignContext(context.Context, string, string) (bool, []string, string, error) {
|
||||
return true, nil, "", nil
|
||||
}
|
||||
func (f *fakeRunMtop) FetchItemsPage(context.Context, string, int, int) (*mtop.ItemListResult, error) {
|
||||
return nil, nil
|
||||
}
|
||||
func (f *fakeRunMtop) FetchAllItems(context.Context, string, int, int) (*mtop.ItemListResult, error) {
|
||||
return nil, nil
|
||||
}
|
||||
func (f *fakeRunMtop) PublishItem(context.Context, string, mtop.PublishItemRequest) (*mtop.PublishItemResult, error) {
|
||||
return nil, nil
|
||||
}
|
||||
func (f *fakeRunMtop) RefreshTokenWithDeviceIDContext(_ context.Context, _ string, _ string) (*mtop.RefreshResult, error) {
|
||||
return &mtop.RefreshResult{AccessToken: f.token}, nil
|
||||
}
|
||||
|
||||
// fakeWSConn 实现 WSConn,可控地投递消息并阻塞到 ctx 取消。
|
||||
type fakeWSConn struct {
|
||||
mu sync.Mutex
|
||||
closed bool
|
||||
tokens []string
|
||||
sentTexts []string
|
||||
sentImages []string
|
||||
heartbeatDone chan struct{}
|
||||
// onReceive 在 ReceiveLoop 启动时被调用,参数是 onMessage 回调,便于测试投递消息。
|
||||
onReceive func(onMessage func(map[string]any))
|
||||
// recvBlock 控制 ReceiveLoop 是否阻塞到 ctx 取消(默认 true)。
|
||||
recvBlock bool
|
||||
}
|
||||
|
||||
func (f *fakeWSConn) HeartbeatLoop(ctx context.Context, _ time.Duration) error {
|
||||
<-ctx.Done()
|
||||
if f.heartbeatDone != nil {
|
||||
close(f.heartbeatDone)
|
||||
}
|
||||
return ctx.Err()
|
||||
}
|
||||
|
||||
func (f *fakeWSConn) ReceiveLoop(ctx context.Context, onMessage func(map[string]any)) error {
|
||||
if f.onReceive != nil {
|
||||
f.onReceive(onMessage)
|
||||
}
|
||||
if f.recvBlock {
|
||||
<-ctx.Done()
|
||||
return ctx.Err()
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (f *fakeWSConn) Close() error {
|
||||
f.mu.Lock()
|
||||
f.closed = true
|
||||
f.mu.Unlock()
|
||||
return nil
|
||||
}
|
||||
|
||||
func (f *fakeWSConn) SetAccessToken(token string) {
|
||||
f.mu.Lock()
|
||||
f.tokens = append(f.tokens, token)
|
||||
f.mu.Unlock()
|
||||
}
|
||||
|
||||
func (f *fakeWSConn) SendText(_ context.Context, _, _, _, text string) error {
|
||||
f.mu.Lock()
|
||||
f.sentTexts = append(f.sentTexts, text)
|
||||
f.mu.Unlock()
|
||||
return nil
|
||||
}
|
||||
|
||||
func (f *fakeWSConn) SendImage(_ context.Context, _, _, _, url string, _, _ int) error {
|
||||
f.mu.Lock()
|
||||
f.sentImages = append(f.sentImages, url)
|
||||
f.mu.Unlock()
|
||||
return nil
|
||||
}
|
||||
|
||||
// fakeDialer 按预设序列返回连接或错误,第 N 次(1-based)调用返回 dialResults[N-1]。
|
||||
type fakeDialer struct {
|
||||
mu sync.Mutex
|
||||
results []dialResult // 每次.Dial 的结果
|
||||
calls int
|
||||
conns []*fakeWSConn
|
||||
lastCfg ws.Config // 记录最后一次 Dial 的配置(含 AccessToken)
|
||||
}
|
||||
|
||||
type dialResult struct {
|
||||
conn *fakeWSConn
|
||||
err error
|
||||
}
|
||||
|
||||
func (d *fakeDialer) Dial(_ context.Context, cfg ws.Config, _ *slog.Logger) (WSConn, error) {
|
||||
d.mu.Lock()
|
||||
defer d.mu.Unlock()
|
||||
d.lastCfg = cfg
|
||||
idx := d.calls
|
||||
d.calls++
|
||||
if idx >= len(d.results) {
|
||||
// 超出预设:返回最后一个 conn,避免无限重连耗尽测试。
|
||||
if len(d.results) > 0 {
|
||||
last := d.results[len(d.results)-1]
|
||||
return last.conn, last.err
|
||||
}
|
||||
return nil, nil
|
||||
}
|
||||
r := d.results[idx]
|
||||
if r.conn != nil {
|
||||
d.conns = append(d.conns, r.conn)
|
||||
}
|
||||
return r.conn, r.err
|
||||
}
|
||||
|
||||
// newRunAccount 构造一个用 fakeMtop + fakeDialer 的 Account,不触网。
|
||||
func newRunAccount(t *testing.T, mtopClient mtop.Client) (*Account, *recordingHandler, *db.Store, func()) {
|
||||
t.Helper()
|
||||
dbPath := filepath.Join(t.TempDir(), "run.db")
|
||||
d, _, err := db.Open(context.Background(), dbPath)
|
||||
if err != nil {
|
||||
t.Fatalf("Open: %v", err)
|
||||
}
|
||||
store := db.NewStore(d, db.DialectSQLite)
|
||||
store.Users.Create(context.Background(), "admin", "[email protected]", "pw")
|
||||
admin, _ := store.Users.GetByUsername(context.Background(), "admin")
|
||||
store.Cookies.Save(context.Background(), "cid", "unb=123; _m_h5_tk=tk_1;", admin.ID)
|
||||
store.Cookies.SetStatus(context.Background(), "cid", true)
|
||||
|
||||
h := &recordingHandler{}
|
||||
acc := New(Config{
|
||||
CookieID: "cid",
|
||||
CookieStr: "unb=123; _m_h5_tk=tk_1;",
|
||||
Store: store,
|
||||
Handler: h,
|
||||
MTop: mtopClient,
|
||||
})
|
||||
return acc, h, store, func() { d.Close() }
|
||||
}
|
||||
|
||||
// TestRun_ConnectsAndDispatchesMessage 验证 Run 主循环:
|
||||
// 刷新 token → 拨号 WS → ReceiveLoop 投递消息 → dispatch 进 handler 防抖链 → ctx 取消后优雅退出。
|
||||
func TestRun_ConnectsAndDispatchesMessage(t *testing.T) {
|
||||
acc, h, _, cleanup := newRunAccount(t, &fakeRunMtop{token: "tok-1"})
|
||||
defer cleanup()
|
||||
|
||||
conn := &fakeWSConn{
|
||||
recvBlock: true,
|
||||
onReceive: func(onMessage func(map[string]any)) {
|
||||
// 投递一条普通聊天消息。
|
||||
onMessage(map[string]any{
|
||||
"1": map[string]any{
|
||||
"2": "chat-1@goofish",
|
||||
"10": map[string]any{
|
||||
"reminderContent": "你好",
|
||||
"senderUserId": "buyer-1",
|
||||
"senderNick": "买家",
|
||||
"reminderUrl": "fleamarket://message_chat?itemId=item-1&peerUserId=buyer-1",
|
||||
},
|
||||
},
|
||||
})
|
||||
},
|
||||
}
|
||||
acc.wsDialer = &fakeDialer{results: []dialResult{{conn: conn}}}
|
||||
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
runDone := make(chan error, 1)
|
||||
go func() { runDone <- acc.Run(ctx) }()
|
||||
|
||||
// 等待防抖延迟后消息进入 handler。
|
||||
deadline := time.After(3 * time.Second)
|
||||
for {
|
||||
h.mu.Lock()
|
||||
n := len(h.chats)
|
||||
h.mu.Unlock()
|
||||
if n >= 1 {
|
||||
break
|
||||
}
|
||||
select {
|
||||
case <-deadline:
|
||||
cancel()
|
||||
t.Fatalf("Run 未在 3s 内投递消息到 handler,chats=%d", n)
|
||||
default:
|
||||
}
|
||||
time.Sleep(50 * time.Millisecond)
|
||||
}
|
||||
|
||||
// 初始 token 应通过 ws.Config.AccessToken 传给 Dial(非 SetAccessToken)。
|
||||
d := acc.wsDialer.(*fakeDialer)
|
||||
d.mu.Lock()
|
||||
gotToken := d.lastCfg.AccessToken == "tok-1"
|
||||
d.mu.Unlock()
|
||||
if !gotToken {
|
||||
t.Fatal("Dial 未收到 ws.Config.AccessToken=tok-1")
|
||||
}
|
||||
|
||||
// 取消 ctx → Run 应退出。
|
||||
cancel()
|
||||
select {
|
||||
case err := <-runDone:
|
||||
if err != nil && err != context.Canceled {
|
||||
t.Fatalf("Run 退出 err=%v", err)
|
||||
}
|
||||
case <-time.After(3 * time.Second):
|
||||
t.Fatal("Run 未在 ctx 取消后 3s 内退出")
|
||||
}
|
||||
}
|
||||
|
||||
// TestRun_DialFailureIncrementsFailures 拨号失败时 connFailures 递增,
|
||||
// ctx 在重试 sleep 期间取消 → Run 返回 ctx.Err。
|
||||
func TestRun_DialFailureIncrementsFailures(t *testing.T) {
|
||||
acc, _, _, cleanup := newRunAccount(t, &fakeRunMtop{token: "tok-1"})
|
||||
defer cleanup()
|
||||
|
||||
// 拨号始终失败。
|
||||
acc.wsDialer = &fakeDialer{results: []dialResult{{err: errFakeDial}}}
|
||||
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
runDone := make(chan error, 1)
|
||||
go func() { runDone <- acc.Run(ctx) }()
|
||||
|
||||
// 等待首次拨号失败 + 进入重试 sleep。
|
||||
time.Sleep(300 * time.Millisecond)
|
||||
cancel()
|
||||
select {
|
||||
case <-runDone:
|
||||
// Run 应已退出。
|
||||
case <-time.After(3 * time.Second):
|
||||
t.Fatal("拨号失败 + ctx 取消后 Run 未退出")
|
||||
}
|
||||
acc.mu.Lock()
|
||||
failures := acc.connFailures
|
||||
acc.mu.Unlock()
|
||||
if failures < 1 {
|
||||
t.Fatalf("拨号失败应使 connFailures>=1,got %d", failures)
|
||||
}
|
||||
}
|
||||
|
||||
// TestRun_ReceiveLoopEndsTriggersReconnect ReceiveLoop 返回后 Run 应重连(再次拨号成功)。
|
||||
// 断线后 retryDelay 默认 5s;token 冷却 1min 会阻塞第二次 refresh,测试期间后台重置冷却。
|
||||
func TestRun_ReceiveLoopEndsTriggersReconnect(t *testing.T) {
|
||||
acc, _, _, cleanup := newRunAccount(t, &fakeRunMtop{token: "tok-1"})
|
||||
defer cleanup()
|
||||
acc.lastTokenRefresh = time.Time{}
|
||||
|
||||
conn1 := &fakeWSConn{recvBlock: false} // 立即返回,模拟断线
|
||||
conn2 := &fakeWSConn{recvBlock: true} // 第二次连上后阻塞
|
||||
d := &fakeDialer{results: []dialResult{{conn: conn1}, {conn: conn2}}}
|
||||
acc.wsDialer = d
|
||||
|
||||
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)
|
||||
for {
|
||||
d.mu.Lock()
|
||||
calls := d.calls
|
||||
d.mu.Unlock()
|
||||
if calls >= 2 {
|
||||
break
|
||||
}
|
||||
select {
|
||||
case <-deadline:
|
||||
t.Fatalf("Run 未在 8s 内重连,calls=%d", calls)
|
||||
default:
|
||||
}
|
||||
time.Sleep(100 * time.Millisecond)
|
||||
}
|
||||
|
||||
cancel()
|
||||
select {
|
||||
case <-runDone:
|
||||
case <-time.After(3 * time.Second):
|
||||
t.Fatal("重连后 ctx 取消 Run 未退出")
|
||||
}
|
||||
}
|
||||
|
||||
// TestRun_DisabledAccountExits 账号被禁用时 Run 立即退出。
|
||||
func TestRun_DisabledAccountExits(t *testing.T) {
|
||||
acc, _, store, cleanup := newRunAccount(t, &fakeRunMtop{token: "tok-1"})
|
||||
defer cleanup()
|
||||
// 禁用账号。
|
||||
store.Cookies.SetStatus(context.Background(), "cid", false)
|
||||
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
done := make(chan error, 1)
|
||||
go func() { done <- acc.Run(ctx) }()
|
||||
select {
|
||||
case err := <-done:
|
||||
if err != nil {
|
||||
t.Fatalf("禁用账号 Run 应返回 nil,got %v", err)
|
||||
}
|
||||
case <-time.After(2 * time.Second):
|
||||
t.Fatal("禁用账号 Run 应立即退出")
|
||||
}
|
||||
}
|
||||
|
||||
var errFakeDial = fakeDialErr{}
|
||||
|
||||
type fakeDialErr struct{}
|
||||
|
||||
func (fakeDialErr) Error() string { return "fake dial failure" }
|
||||
Reference in new issue
Block a user