Files
Ydisks-Xianyu-Helper/internal/account/manager_extra_test.go
T

707 lines
26 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
package account
import (
"context"
"errors"
"log/slog"
"path/filepath"
"strings"
"sync"
"testing"
"time"
"xianyu-go/internal/db"
"xianyu-go/internal/engine"
"xianyu-go/internal/xianyu/mtop"
"xianyu-go/internal/xianyu/ws"
)
// fakeWSDialer 保存fakeWSDialer,供当前处理流程使用
type fakeWSDialer struct{}
// Dial 负责Dial相关处理。
func (fakeWSDialer) Dial(context.Context, ws.Config, *slog.Logger) (engine.WSConn, error) {
return fakeWSConn{}, nil
}
// fakeWSConn 保存fakeWSConn,供当前处理流程使用
type fakeWSConn struct{}
// Register 负责Register相关处理。
func (fakeWSConn) Register(context.Context, string, string) error { return nil }
// HeartbeatLoop 负责HeartbeatLoop相关处理。
func (fakeWSConn) HeartbeatLoop(ctx context.Context, _ time.Duration) error {
<-ctx.Done()
return ctx.Err()
}
// ReceiveLoop 负责ReceiveLoop相关处理。
func (fakeWSConn) ReceiveLoop(ctx context.Context, _ func(map[string]any)) error {
<-ctx.Done()
return ctx.Err()
}
// Close 关闭当前值。
func (fakeWSConn) Close() error { return nil }
// SendText 负责Send文本相关处理。
func (fakeWSConn) SendText(context.Context, string, string, string, string) error {
return nil
}
// SendImage 负责Send图片相关处理。
func (fakeWSConn) SendImage(context.Context, string, string, string, string, int, int) error {
return nil
}
// fakeMtop 是注入 engine.Account 的可控 mtop 客户端,避免真实网络。
// refreshErr 非空时 RefreshToken 返回该错误;block 非空时阻塞到该 chan
// 关闭或 ctx 取消(用于让 Run 挂起、模拟"账号在线运行中")。
// fakeMtop 保存fakeMtop,供当前处理流程使用
type fakeMtop struct {
refreshErr error
block chan struct{}
calls int
mu sync.Mutex
}
// RefreshTokenWithDeviceIDContext 刷新令牌WithDeviceID上下文。
func (f *fakeMtop) RefreshTokenWithDeviceIDContext(ctx context.Context, _, _ string) (*mtop.RefreshResult, error) {
f.mu.Lock()
f.calls++
f.mu.Unlock()
if f.block != nil {
select {
case <-f.block:
case <-ctx.Done():
return &mtop.RefreshResult{UpdatedCookies: ""}, ctx.Err()
}
}
if f.refreshErr != nil {
return &mtop.RefreshResult{}, f.refreshErr
}
return &mtop.RefreshResult{AccessToken: "fake-token"}, nil
}
// FetchUserProfile 负责Fetch用户Profile相关处理。
func (f *fakeMtop) FetchUserProfile(context.Context, string) (*mtop.UserProfileResult, error) {
return nil, nil
}
// ConsignContext 负责Consign上下文相关处理。
func (f *fakeMtop) ConsignContext(context.Context, string, string) (bool, []string, string, error) {
return false, nil, "", nil
}
// FetchItemsPage 负责Fetch商品列表页码相关处理。
func (f *fakeMtop) FetchItemsPage(context.Context, string, int, int) (*mtop.ItemListResult, error) {
return nil, nil
}
// FetchAllItems 负责FetchAll商品列表相关处理。
func (f *fakeMtop) FetchAllItems(context.Context, string, int, int) (*mtop.ItemListResult, error) {
return nil, nil
}
// PublishItem 负责发布商品相关处理。
func (f *fakeMtop) PublishItem(context.Context, string, mtop.PublishItemRequest) (*mtop.PublishItemResult, error) {
return nil, nil
}
// newTestStore 构造临时 SQLite + 已初始化的 admin,返回 store 与 cleanup。
func newTestStore(t *testing.T) (*db.Store, func()) {
t.Helper()
// dbPath 保存db路径,供当前处理流程使用
dbPath := filepath.Join(t.TempDir(), "test.db")
// d、err 保存d、err,供当前处理流程使用
d, _, err := db.Open(context.Background(), dbPath)
if err != nil {
t.Fatalf("Open: %v", err)
}
// store 保存store,供当前处理流程使用
store := db.NewStore(d, db.DialectSQLite)
store.Users.Create(context.Background(), "admin", "a@e.com", "pw")
return store, func() { d.Close() }
}
// newManagerWithAccount 构造 Manager 并向 DB 写入一个启用的账号。
func newManagerWithAccount(t *testing.T, cookieID, cookieValue string) (*Manager, *db.Store, func()) {
t.Helper()
// store、cleanup 保存store、cleanup,供当前处理流程使用
store, cleanup := newTestStore(t)
// admin 保存admin,供当前处理流程使用
admin, _ := store.Users.GetByUsername(context.Background(), "admin")
if // err 保存err,供当前处理流程使用
err := store.Cookies.Save(context.Background(), cookieID, cookieValue, admin.ID); err != nil {
cleanup()
t.Fatalf("Save cookie: %v", err)
}
if // err 保存err,供当前处理流程使用
err := store.Cookies.SetStatus(context.Background(), cookieID, true); err != nil {
cleanup()
t.Fatalf("SetStatus: %v", err)
}
return NewManager(store, noopHandler{}, nil), store, cleanup
}
// startAccountWithMtop 用自定义 mtop 客户端启动账号,返回 runCtx 的 cancel。
// runCtx 在测试结束 / Stop 时取消以回收 Run goroutine。
// startAccountWithMtop 负责开始账号WithMtop相关处理。
func startAccountWithMtop(t *testing.T, mgr *Manager, cookieID, cookieValue string, mtopClient mtop.Client) context.CancelFunc {
t.Helper()
// runCtx、cancel 保存运行Ctx、cancel,供当前处理流程使用
runCtx, cancel := context.WithCancel(context.Background())
// acc 保存acc,供当前处理流程使用
acc := engine.New(engine.Config{
CookieID: cookieID,
CookieStr: cookieValue,
Store: mgr.store,
Handler: mgr.handler,
Logger: mgr.logger,
MTop: mtopClient,
WSDialer: fakeWSDialer{},
})
// accCtx、accCancel 保存accCtx、acc取消,供当前处理流程使用
accCtx, accCancel := context.WithCancel(runCtx)
// ma 保存ma,供当前处理流程使用
ma := &managedAccount{
cookieID: cookieID,
acc: acc,
cancel: accCancel,
done: make(chan struct{}),
}
mgr.mu.Lock()
mgr.runCtx = runCtx
mgr.accounts[cookieID] = ma
mgr.mu.Unlock()
go func() {
defer close(ma.done)
ma.err = acc.Run(accCtx)
}()
return cancel
}
// TestSender 验证 Sender 在账号在线时返回 MessageSender,离线时返回 false。
func TestSender(t *testing.T) {
// mgr、cleanup 保存mgr、cleanup,供当前处理流程使用
mgr, _, cleanup := newManagerWithAccount(t, "acc-on", "unb=1; _m_h5_tk=t1_1;")
defer cleanup()
// 离线:未启动。
if s, ok := mgr.Sender("acc-on"); ok || s != nil {
t.Fatalf("未启动账号 Sender 应返回 (nil,false),got (%v,%v)", s, ok)
}
if // s、ok 保存s、ok,供当前处理流程使用
s, ok := mgr.Sender("acc-missing"); ok || s != nil {
t.Fatalf("不存在账号 Sender 应返回 (nil,false),got (%v,%v)", s, ok)
}
// 用阻塞型 mtop 启动,让 Run 一直挂起,账号保持"运行中"。
mtopClient := &fakeMtop{block: make(chan struct{})}
// cancel 保存取消,供当前处理流程使用
cancel := startAccountWithMtop(t, mgr, "acc-on", "unb=1; _m_h5_tk=t1_1;", mtopClient)
defer cancel()
// 给 Run 一点时间进入 refreshToken 阻塞。
time.Sleep(50 * time.Millisecond)
// s、ok 保存s、ok,供当前处理流程使用
s, ok := mgr.Sender("acc-on")
if !ok || s == nil {
t.Fatalf("在线账号 Sender 应返回 (sender,true)")
}
// 停止后应回到 (nil,false)。Stop 会取消 accCtx,refreshToken 在阻塞 select
// 上收到 ctx.Done() 返回,Run 退出,不会进入真实 WS dial。
mgr.Stop("acc-on")
if // s、ok 保存s、ok,供当前处理流程使用
s, ok := mgr.Sender("acc-on"); ok || s != nil {
t.Fatalf("停止后 Sender 应返回 (nil,false),got (%v,%v)", s, ok)
}
}
// TestRuntimeStatuses 验证多账号状态快照聚合,覆盖:
// - 运行中账号(done 未关):状态原样返回
// - done 已关 + err=nil:覆盖为 RuntimeError + "账号服务已退出"
// - done 已关 + err=非 context.Canceled:覆盖为 RuntimeError + err 文案
// - done 已关 + err=context.Canceled:覆盖为 RuntimeError + "账号服务已退出"
// - done 已关 + 状态=RuntimeAuthExpired:保持原状态(通过 session-expired 走 handleMaxFailures)
// - done 已关 + 状态=RuntimeVerificationRequired:保持原状态(通过验证类错误 + 取消)
//
// TestRuntimeStatuses 负责TestRuntimeStatuses相关处理。
func TestRuntimeStatuses(t *testing.T) {
// mgr、store、cleanup 保存mgr、store、cleanup,供当前处理流程使用
mgr, store, cleanup := newManagerWithAccount(t, "seed", "unb=1; _m_h5_tk=t1_1;")
defer cleanup()
// admin 保存admin,供当前处理流程使用
admin, _ := store.Users.GetByUsername(context.Background(), "admin")
// 1) 运行中账号:阻塞型 mtop 让 Run 挂起。
runMtop := &fakeMtop{block: make(chan struct{})}
// runCancel 保存运行取消,供当前处理流程使用
runCancel := startAccountWithMtop(t, mgr, "running", "unb=10; _m_h5_tk=t_1;", runMtop)
defer runCancel()
time.Sleep(50 * time.Millisecond)
// 2) done 已关 + err=nil(手动构造 managedAccount,不跑 Run)。
nilDoneAcc := engine.New(engine.Config{
CookieID: "nil-done", CookieStr: "unb=2; _m_h5_tk=t_1;",
Store: store, Handler: noopHandler{}, MTop: &fakeMtop{},
})
// nilDoneMA 保存nilDoneMA,供当前处理流程使用
nilDoneMA := &managedAccount{cookieID: "nil-done", acc: nilDoneAcc, done: make(chan struct{})}
close(nilDoneMA.done) // err 为 nil
mgr.mu.Lock()
mgr.accounts["nil-done"] = nilDoneMA
mgr.mu.Unlock()
// 3) done 已关 + err=非 canceled。
errDoneAcc := engine.New(engine.Config{
CookieID: "err-done", CookieStr: "unb=3; _m_h5_tk=t_1;",
Store: store, Handler: noopHandler{}, MTop: &fakeMtop{},
})
// errDoneMA 保存errDoneMA,供当前处理流程使用
errDoneMA := &managedAccount{cookieID: "err-done", acc: errDoneAcc, done: make(chan struct{}), err: errors.New("boom-failure")}
close(errDoneMA.done)
mgr.mu.Lock()
mgr.accounts["err-done"] = errDoneMA
mgr.mu.Unlock()
// 4) done 已关 + err=context.Canceled。
canceledAcc := engine.New(engine.Config{
CookieID: "canceled", CookieStr: "unb=4; _m_h5_tk=t_1;",
Store: store, Handler: noopHandler{}, MTop: &fakeMtop{},
})
// canceledMA 保存canceledMA,供当前处理流程使用
canceledMA := &managedAccount{cookieID: "canceled", acc: canceledAcc, done: make(chan struct{}), err: context.Canceled}
close(canceledMA.done)
mgr.mu.Lock()
mgr.accounts["canceled"] = canceledMA
mgr.mu.Unlock()
// 5) 状态=RuntimeAuthExpired(session-expired 错误让 Run 走到 handleMaxFailures 慢重试)。
// 新行为:账号不再硬退出,而是保持 goroutine 存活、慢重试,状态停在 RuntimeAuthExpired。
store.Cookies.Save(context.Background(), "auth-exp", "unb=5; _m_h5_tk=t_1;", admin.ID)
// authMgr 保存authMgr,供当前处理流程使用
authMgr := mgr
// authCancel 保存auth取消,供当前处理流程使用
authCancel := startAccountWithMtop(t, authMgr, "auth-exp", "unb=5; _m_h5_tk=t_1;",
&fakeMtop{refreshErr: errors.New("token API 登录凭证已失效: ret=[FAIL_SYS_SESSION_EXPIRED] status=403")})
defer authCancel()
// 等待 Run 进入 RuntimeAuthExpired 慢重试(不再硬退出,done 不关闭)。
if !waitForState(mgr, "auth-exp", engine.RuntimeAuthExpired, 2*time.Second) {
t.Fatal("auth-exp 账号未在超时内进入 RuntimeAuthExpired")
}
// 6) done 已关 + 状态=RuntimeVerificationRequired(验证类错误 + 立即取消 ctx)。
store.Cookies.Save(context.Background(), "verify", "unb=6; _m_h5_tk=t_1;", admin.ID)
// verifyMtop 保存verifyMtop,供当前处理流程使用
verifyMtop := &fakeMtop{refreshErr: errors.New("FAIL_SYS_USER_VALIDATE: captcha required")}
// verifyCancel 保存verify取消,供当前处理流程使用
verifyCancel := startAccountWithMtop(t, mgr, "verify", "unb=6; _m_h5_tk=t_1;", verifyMtop)
// 让 Run 进入一次 refreshToken → setRuntimeError(RuntimeVerificationRequired) → sleepCtx。
time.Sleep(80 * time.Millisecond)
verifyCancel() // 取消 runCtx,sleepCtx 返回 ctx.Err(),Run 退出,done 关闭。
if !waitForDone(mgr, "verify", 2*time.Second) {
t.Fatal("verify 账号未在超时内退出")
}
// statuses 保存statuses,供当前处理流程使用
statuses := mgr.RuntimeStatuses()
// 运行中:应有该 key,状态非空。
if s, ok := statuses["running"]; !ok || s.State == "" {
t.Fatalf("running 应有非空状态,got %+v ok=%v", s, ok)
}
// nil-done:覆盖为 RuntimeError + "账号服务已退出"。
if s := statuses["nil-done"]; s.State != engine.RuntimeError || s.Message != "账号服务已退出" {
t.Fatalf("nil-done 状态错误,got %+v", s)
}
// err-done:覆盖为 RuntimeError + err 文案。
if s := statuses["err-done"]; s.State != engine.RuntimeError || s.Message != "boom-failure" {
t.Fatalf("err-done 状态错误,got %+v", s)
}
// canceled:覆盖为 RuntimeError + "账号服务已退出"(err==context.Canceled 跳过覆盖文案)。
if s := statuses["canceled"]; s.State != engine.RuntimeError || s.Message != "账号服务已退出" {
t.Fatalf("canceled 状态错误,got %+v", s)
}
// auth-exp:保持 RuntimeAuthExpired,不被覆盖为 RuntimeError。
if s := statuses["auth-exp"]; s.State != engine.RuntimeAuthExpired {
t.Fatalf("auth-exp 应保持 %s,got %+v", engine.RuntimeAuthExpired, s)
}
// verify:保持 RuntimeVerificationRequired,不被覆盖。
if s := statuses["verify"]; s.State != engine.RuntimeVerificationRequired {
t.Fatalf("verify 应保持 %s,got %+v", engine.RuntimeVerificationRequired, s)
}
// 聚合数量应包含全部 6 个账号。
if len(statuses) != 6 {
t.Fatalf("状态数量应为 6,got %d (%+v)", len(statuses), statuses)
}
}
// waitForDone 轮询等待某账号 done 关闭。
func waitForDone(mgr *Manager, cookieID string, timeout time.Duration) bool {
// deadline 保存deadline,供当前处理流程使用
deadline := time.Now().Add(timeout)
for time.Now().Before(deadline) {
mgr.mu.Lock()
// ma、ok 保存ma、ok,供当前处理流程使用
ma, ok := mgr.accounts[cookieID]
mgr.mu.Unlock()
if !ok {
return false
}
select {
case <-ma.done:
return true
default:
}
time.Sleep(10 * time.Millisecond)
}
return false
}
// waitForState 轮询等待某账号进入指定运行时状态。
func waitForState(mgr *Manager, cookieID, want string, timeout time.Duration) bool {
// deadline 保存deadline,供当前处理流程使用
deadline := time.Now().Add(timeout)
for time.Now().Before(deadline) {
mgr.mu.Lock()
// ma、ok 保存ma、ok,供当前处理流程使用
ma, ok := mgr.accounts[cookieID]
mgr.mu.Unlock()
if ok && ma.acc != nil && ma.acc.RuntimeStatus().State == want {
return true
}
time.Sleep(10 * time.Millisecond)
}
return false
}
// TestRestart 验证重启账号:停止旧实例→读取最新 DB cookie→启动新实例。
func TestRestart(t *testing.T) {
// mgr、store、cleanup 保存mgr、store、cleanup,供当前处理流程使用
mgr, store, cleanup := newManagerWithAccount(t, "restart-acc", "unb=1; _m_h5_tk=old;")
defer cleanup()
// admin 保存admin,供当前处理流程使用
admin, _ := store.Users.GetByUsername(context.Background(), "admin")
// 用阻塞 mtop 启动旧实例,使其保持运行。
oldMtop := &fakeMtop{block: make(chan struct{})}
// cancel 保存取消,供当前处理流程使用
cancel := startAccountWithMtop(t, mgr, "restart-acc", "unb=1; _m_h5_tk=old;", oldMtop)
defer cancel()
time.Sleep(50 * time.Millisecond)
// oldMA 保存oldMA,供当前处理流程使用
oldMA, _ := mgr.getInstanceInternal("restart-acc")
if oldMA == nil {
t.Fatal("旧实例应存在")
}
// 更新 DB cookie 为新值,模拟外部刷新。
store.Cookies.Save(context.Background(), "restart-acc", "unb=1; _m_h5_tk=new-refreshed;", admin.ID)
// ctx、ctxCancel 保存ctx、ctx取消,供当前处理流程使用
ctx, ctxCancel := context.WithTimeout(context.Background(), 5*time.Second)
defer ctxCancel()
if // err 保存err,供当前处理流程使用
err := mgr.Restart(ctx, "restart-acc"); err != nil {
t.Fatalf("Restart: %v", err)
}
// 新实例应存在且 != 旧实例。
newMA, ok := mgr.getInstanceInternal("restart-acc")
if !ok || newMA == nil {
t.Fatal("Restart 后应存在新实例")
}
if newMA == oldMA {
t.Fatal("Restart 后应是新实例,不是旧实例")
}
// 新实例的 CookieStr 应反映最新 DB 值。
if got := newMA.acc.CurrentCookieStr(); got != "unb=1; _m_h5_tk=new-refreshed;" {
t.Fatalf("新实例 CookieStr=%q want new-refreshed", got)
}
// 旧实例的 done 应已关闭(被 Stop)。
select {
case <-oldMA.done:
default:
t.Fatal("旧实例应已被停止(done 关闭)")
}
// 清理新实例。
mgr.Stop("restart-acc")
}
// TestRestart_GetDetailsError 验证 Restart 读不存在的账号详情应返回包装错误。
func TestRestart_GetDetailsError(t *testing.T) {
// mgr、cleanup 保存mgr、cleanup,供当前处理流程使用
mgr, _, cleanup := newManagerWithAccount(t, "seed", "unb=1; _m_h5_tk=t;")
defer cleanup()
// ctx、ctxCancel 保存ctx、ctx取消,供当前处理流程使用
ctx, ctxCancel := context.WithTimeout(context.Background(), 2*time.Second)
defer ctxCancel()
// err 保存err,供当前处理流程使用
err := mgr.Restart(ctx, "no-such-account")
if err == nil {
t.Fatal("Restart 不存在账号应返回错误")
}
if !strings.Contains(err.Error(), "读取账号详情失败") {
t.Fatalf("错误应包含'读取账号详情失败',got %v", err)
}
}
// TestStart_SkipsRunning 验证对运行中账号调用 Start 跳过启动。
func TestStart_SkipsRunning(t *testing.T) {
// mgr、cleanup 保存mgr、cleanup,供当前处理流程使用
mgr, _, cleanup := newManagerWithAccount(t, "running-acc", "unb=1; _m_h5_tk=t;")
defer cleanup()
// runMtop 保存运行Mtop,供当前处理流程使用
runMtop := &fakeMtop{block: make(chan struct{})}
// cancel 保存取消,供当前处理流程使用
cancel := startAccountWithMtop(t, mgr, "running-acc", "unb=1; _m_h5_tk=t;", runMtop)
defer cancel()
time.Sleep(50 * time.Millisecond)
// original 保存original,供当前处理流程使用
original, _ := mgr.getInstanceInternal("running-acc")
// ctx、ctxCancel 保存ctx、ctx取消,供当前处理流程使用
ctx, ctxCancel := context.WithTimeout(context.Background(), 2*time.Second)
defer ctxCancel()
if // err 保存err,供当前处理流程使用
err := mgr.Start(ctx, "running-acc", "unb=1; _m_h5_tk=different;"); err != nil {
t.Fatalf("Start 运行中账号应返回 nil,got %v", err)
}
// 应仍是同一实例(未被替换)。
after, _ := mgr.getInstanceInternal("running-acc")
if after != original {
t.Fatal("Start 运行中账号不应替换实例")
}
if // got 保存got,供当前处理流程使用
got := after.acc.CurrentCookieStr(); got != "unb=1; _m_h5_tk=t;" {
t.Fatalf("实例 CookieStr 不应变,got %q", got)
}
mgr.Stop("running-acc")
}
// TestStart_RestartsExited 验证 Manager.Start 在"账号已存在且 done 已关"路径上
// 清理旧实例并重启新实例。该路径曾是双重解锁 bug(分支内 Unlock 后函数末尾再次
// Unlock),已修复:现在持锁 delete 后由函数末尾单次 Unlock。
// TestStart_RestartsExited 负责Test开始RestartsExited相关处理。
func TestStart_RestartsExited(t *testing.T) {
// mgr、cleanup 保存mgr、cleanup,供当前处理流程使用
mgr, _, cleanup := newManagerWithAccount(t, "exited-acc", "unb=1; _m_h5_tk=t;")
defer cleanup()
// 注入一个已退出的 managedAccount(done 已关),无 Run goroutine。
exitedAcc := engine.New(engine.Config{
CookieID: "exited-acc", CookieStr: "unb=1; _m_h5_tk=old;",
Store: mgr.store, Handler: noopHandler{}, MTop: &fakeMtop{},
})
// exitedMA 保存exitedMA,供当前处理流程使用
exitedMA := &managedAccount{cookieID: "exited-acc", acc: exitedAcc, done: make(chan struct{}), err: context.Canceled}
close(exitedMA.done)
mgr.mu.Lock()
mgr.accounts["exited-acc"] = exitedMA
mgr.mu.Unlock()
// ctx、ctxCancel 保存ctx、ctx取消,供当前处理流程使用
ctx, ctxCancel := context.WithCancel(context.Background())
defer ctxCancel()
mgr.mu.Lock()
mgr.runCtx = ctx
mgr.mu.Unlock()
if // err 保存err,供当前处理流程使用
err := mgr.store.Cookies.Save(ctx, "exited-acc", "unb=1; _m_h5_tk=brand-new;", 0); err != nil {
t.Fatal(err)
}
if // err 保存err,供当前处理流程使用
err := mgr.Start(ctx, "exited-acc", "unb=1; _m_h5_tk=brand-new;"); err != nil {
t.Fatalf("Start 已退出账号应成功,got %v", err)
}
// newMA、ok 保存newMA、ok,供当前处理流程使用
newMA, ok := mgr.getInstanceInternal("exited-acc")
if !ok {
t.Fatal("Start 后应存在新实例")
}
if newMA == exitedMA {
t.Fatal("应替换为全新实例")
}
if // got 保存got,供当前处理流程使用
got := newMA.acc.CurrentCookieStr(); got != "unb=1; _m_h5_tk=brand-new;" {
t.Fatalf("新实例 CookieStr=%q want brand-new", got)
}
// done 不应已关闭(新实例在运行)。
select {
case <-newMA.done:
t.Fatal("新实例 done 不应已关闭")
default:
}
mgr.Stop("exited-acc")
}
// TestStartAll_LoadError 验证 StartAll 在 DB 加载失败时返回包装错误。
// 通过提前关闭底层 sql.DB 触发运行时凭证查询错误。
// TestStartAll_LoadError 负责Test开始AllLoad错误相关处理。
func TestStartAll_LoadError(t *testing.T) {
// store、cleanup 保存store、cleanup,供当前处理流程使用
store, cleanup := newTestStore(t)
defer cleanup()
// mgr 保存mgr,供当前处理流程使用
mgr := NewManager(store, noopHandler{}, nil)
// 提前关闭 DB 让 ListEnabledRuntimeCredentials 失败。
if err := store.DB.Close(); err != nil {
t.Fatalf("关闭 DB: %v", err)
}
// ctx、cancel 保存ctx、cancel,供当前处理流程使用
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
// err 保存err,供当前处理流程使用
err := mgr.StartAll(ctx)
if err == nil {
t.Fatal("StartAll 在 DB 加载失败时应返回错误")
}
if !strings.Contains(err.Error(), "加载账号失败") {
t.Fatalf("错误应包含'加载账号失败',got %v", err)
}
}
// TestStartAll_DisabledNotStarted 验证 DB 中禁用的账号不被启动。
func TestStartAll_DisabledNotStarted(t *testing.T) {
// store、cleanup 保存store、cleanup,供当前处理流程使用
store, cleanup := newTestStore(t)
defer cleanup()
// admin 保存admin,供当前处理流程使用
admin, _ := store.Users.GetByUsername(context.Background(), "admin")
// 启用 + 禁用 + 启用。
store.Cookies.Save(context.Background(), "on1", "unb=1; _m_h5_tk=t;", admin.ID)
store.Cookies.SetStatus(context.Background(), "on1", true)
store.Cookies.Save(context.Background(), "off1", "unb=2; _m_h5_tk=t;", admin.ID)
store.Cookies.SetStatus(context.Background(), "off1", false)
store.Cookies.Save(context.Background(), "on2", "unb=3; _m_h5_tk=t;", admin.ID)
store.Cookies.SetStatus(context.Background(), "on2", true)
// 用阻塞 mtop 的 Manager:直接构造,使所有启动账号都挂起、不触发真实网络。
mgr := NewManager(store, noopHandler{}, nil)
// ctx、cancel 保存ctx、cancel,供当前处理流程使用
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
if // err 保存err,供当前处理流程使用
err := mgr.StartAll(ctx); err != nil {
t.Fatalf("StartAll: %v", err)
}
// 启用的应存在,禁用的不应存在。
if _, ok := mgr.GetInstance("on1"); !ok {
t.Fatal("on1 应被启动")
}
if // ok 保存ok,供当前处理流程使用
_, ok := mgr.GetInstance("on2"); !ok {
t.Fatal("on2 应被启动")
}
if // ok 保存ok,供当前处理流程使用
_, ok := mgr.GetInstance("off1"); ok {
t.Fatal("off1 已禁用不应被启动")
}
// StopAll 应清空全部。
mgr.StopAll()
// id 表示当前遍历过程中的标识
for _, id := range []string{"on1", "on2", "off1"} {
if // ok 保存ok,供当前处理流程使用
_, ok := mgr.GetInstance(id); ok {
t.Fatalf("StopAll 后 %s 仍存在", id)
}
}
}
// TestStop_Nonexistent 验证停止不存在的账号是 no-op,不 panic。
func TestStop_Nonexistent(t *testing.T) {
// mgr、cleanup 保存mgr、cleanup,供当前处理流程使用
mgr, _, cleanup := newManagerWithAccount(t, "seed", "unb=1; _m_h5_tk=t;")
defer cleanup()
// 不应 panic。
mgr.Stop("does-not-exist")
}
// TestConcurrency 用 -race 验证多 goroutine 并发访问 GetInstance/Sender/RuntimeStatuses 不 race。
func TestConcurrency(t *testing.T) {
// mgr、store、cleanup 保存mgr、store、cleanup,供当前处理流程使用
mgr, store, cleanup := newManagerWithAccount(t, "conc-acc", "unb=1; _m_h5_tk=t;")
defer cleanup()
// admin 保存admin,供当前处理流程使用
admin, _ := store.Users.GetByUsername(context.Background(), "admin")
// 多个启用账号。
for _, id := range []string{"conc-2", "conc-3"} {
store.Cookies.Save(context.Background(), id, "unb=2; _m_h5_tk=t;", admin.ID)
store.Cookies.SetStatus(context.Background(), id, true)
}
// 用阻塞 mtop 让账号保持运行,避免 Run 退出引入噪声。
for _, id := range []string{"conc-acc", "conc-2", "conc-3"} {
// mtopClient 保存mtopClient,供当前处理流程使用
mtopClient := &fakeMtop{block: make(chan struct{})}
// c 保存c,供当前处理流程使用
c := startAccountWithMtop(t, mgr, id, "unb=1; _m_h5_tk=t;", mtopClient)
defer c()
}
time.Sleep(60 * time.Millisecond)
// wg 保存wg,供当前处理流程使用
var wg sync.WaitGroup
for // i 保存i,供当前处理流程使用
i := 0; i < 20; i++ {
wg.Add(3)
go func() {
defer wg.Done()
for // j 保存j,供当前处理流程使用
j := 0; j < 100; j++ {
_, _ = mgr.GetInstance("conc-acc")
}
}()
go func() {
defer wg.Done()
for // j 保存j,供当前处理流程使用
j := 0; j < 100; j++ {
_, _ = mgr.Sender("conc-2")
}
}()
go func() {
defer wg.Done()
for // j 保存j,供当前处理流程使用
j := 0; j < 100; j++ {
_ = mgr.RuntimeStatuses()
}
}()
}
wg.Wait()
mgr.StopAll()
}
// getInstanceInternal 返回内部 managedAccount(测试用)。
func (m *Manager) getInstanceInternal(cookieID string) (*managedAccount, bool) {
m.mu.Lock()
defer m.mu.Unlock()
// ma、ok 保存ma、ok,供当前处理流程使用
ma, ok := m.accounts[cookieID]
return ma, ok
}