chore: checkpoint repaired xianyu-go baseline

This commit is contained in:
Christ committed 2026-07-08 03:46:15 +08:00
1 parent 62705c524d
commit 3d37ff7917
119 files changed
+20086 -2085

No files matched your search

+22 -3
View File
@@ -11,6 +11,7 @@ import (
"time"
"github.com/playwright-community/playwright-go"
"golang.org/x/sync/singleflight"
"xianyu-go/internal/xianyu"
)
@@ -64,6 +65,7 @@ type Manager struct {
pool map[string]*poolEntry
maxSize int
idleTTL time.Duration
creates singleflight.Group
// 允许测试注入自定义 playwright / 安装函数。
installFn func() error
@@ -176,9 +178,26 @@ func (m *Manager) acquireEntry(cookieID, cookieStr string, headless bool) (*pool
}
m.mu.Unlock()
// 池满,淘汰最久未用。
m.evictIfNeeded()
return m.createEntry(cookieID, cookieStr, headless)
created, err, _ := m.creates.Do(cookieID, func() (any, error) {
m.mu.Lock()
if e, ok := m.pool[cookieID]; ok && e.browser != nil && e.browser.IsConnected() {
e.lastUsed = time.Now()
m.mu.Unlock()
return e, nil
}
m.mu.Unlock()
// 池满,淘汰最久未用。
m.evictIfNeeded()
return m.createEntry(cookieID, cookieStr, headless)
})
if err != nil {
return nil, err
}
entry, ok := created.(*poolEntry)
if !ok || entry == nil {
return nil, fmt.Errorf("浏览器池创建返回异常")
}
return entry, nil
}
func (m *Manager) createEntry(cookieID, cookieStr string, headless bool) (*poolEntry, error) {
+126
View File
@@ -0,0 +1,126 @@
package browser
import (
"testing"
"time"
playwright "github.com/playwright-community/playwright-go"
)
// TestChromiumLaunchArgs 验证启动参数含关键安全/反检测项。
func TestChromiumLaunchArgs(t *testing.T) {
args := chromiumLaunchArgs()
if len(args) == 0 {
t.Fatal("应返回非空参数列表")
}
want := []string{"--no-sandbox", "--disable-dev-shm-usage", "--disable-blink-features=AutomationControlled", "--lang=zh-CN"}
for _, w := range want {
found := false
for _, a := range args {
if a == w {
found = true
break
}
}
if !found {
t.Errorf("缺少关键参数 %s", w)
}
}
}
// newTestManager 构造一个不触网的 Manager(pool 空,maxSize 小便于测试驱逐)。
func newTestManager(maxSize int) *Manager {
return &Manager{
logger: nil,
pool: make(map[string]*poolEntry),
maxSize: maxSize,
idleTTL: 5 * time.Minute,
}
}
// TestTouchUpdatesLastUsed touch 命中池中条目时更新 lastUsed。
func TestTouchUpdatesLastUsed(t *testing.T) {
m := newTestManager(3)
old := time.Now().Add(-time.Hour)
m.pool["c1"] = &poolEntry{cookieID: "c1", lastUsed: old}
m.touch("c1")
if m.pool["c1"].lastUsed.Equal(old) {
t.Fatal("touch 应更新 lastUsed")
}
// touch 不存在的条目应 no-op 不 panic。
m.touch("no-such")
}
// TestEvictRemovesEntry evict 删除指定条目(nil browser 时 closeEntry 为 no-op)。
func TestEvictRemovesEntry(t *testing.T) {
m := newTestManager(3)
m.pool["c1"] = &poolEntry{cookieID: "c1"}
m.pool["c2"] = &poolEntry{cookieID: "c2"}
m.evict("c1")
if _, ok := m.pool["c1"]; ok {
t.Fatal("evict 应删除 c1")
}
if _, ok := m.pool["c2"]; !ok {
t.Fatal("c2 应保留")
}
// evict 不存在的条目不 panic。
m.evict("no-such")
}
// TestEvictIfNeededEvictsOldest 池满时驱逐最久未用的条目。
func TestEvictIfNeededEvictsOldest(t *testing.T) {
m := newTestManager(2)
m.pool["c1"] = &poolEntry{cookieID: "c1", lastUsed: time.Now().Add(-2 * time.Hour)}
m.pool["c2"] = &poolEntry{cookieID: "c2", lastUsed: time.Now()}
m.evictIfNeeded() // 池满(2 == maxSize),应驱逐 c1(最旧)
if _, ok := m.pool["c1"]; ok {
t.Fatal("应驱逐最旧的 c1")
}
if _, ok := m.pool["c2"]; !ok {
t.Fatal("c2 应保留")
}
}
// TestEvictIfNeededNoopWhenUnderLimit 池未满时不驱逐。
func TestEvictIfNeededNoopWhenUnderLimit(t *testing.T) {
m := newTestManager(5)
m.pool["c1"] = &poolEntry{cookieID: "c1", lastUsed: time.Now()}
m.evictIfNeeded()
if _, ok := m.pool["c1"]; !ok {
t.Fatal("未满不应驱逐")
}
}
// TestMarshalCookies 导出包装器等价 cookieMarshal。
func TestMarshalCookies(t *testing.T) {
got := MarshalCookies(map[string]string{"unb": "1", "cna": "xx"})
// map 顺序不保证,逐项检查。
if !contains(got, "unb=1") || !contains(got, "cna=xx") {
t.Fatalf("MarshalCookies=%q", got)
}
}
// TestCookiesToMap playwright.Cookie 切片转 map。
func TestCookiesToMap(t *testing.T) {
cs := []playwright.Cookie{
{Name: "unb", Value: "123"},
{Name: "_m_h5_tk", Value: "tok"},
}
m := cookiesToMap(cs)
if m["unb"] != "123" || m["_m_h5_tk"] != "tok" || len(m) != 2 {
t.Fatalf("cookiesToMap=%+v", m)
}
// 空切片。
if m := cookiesToMap(nil); len(m) != 0 {
t.Fatalf("空切片应返回空 map,got %+v", m)
}
}
func contains(s, sub string) bool {
for i := 0; i+len(sub) <= len(s); i++ {
if s[i:i+len(sub)] == sub {
return true
}
}
return false
}
+1 -1
View File
@@ -39,7 +39,7 @@ var orderStatusMap = map[int]string{
func (m *Manager) FetchOrderDetail(ctx context.Context, orderID, cookieID, cookieValue string, requireSpec ...bool) (*OrderDetail, error) {
needsSpec := len(requireSpec) > 0 && requireSpec[0]
// 优先调用稳定的 MTop 详情接口;页面自动化只作为规格字段的兼容兜底。
if direct, directErr := (&mtop.Client{}).FetchOrderDetail(ctx, cookieValue, orderID); directErr == nil && direct != nil && direct.Amount != "" &&
if direct, directErr := mtop.NewClient().FetchOrderDetail(ctx, cookieValue, orderID); directErr == nil && direct != nil && direct.Amount != "" &&
(!needsSpec || (direct.SpecName != "" && direct.SpecValue != "")) {
return &OrderDetail{
OrderID: orderID, Quantity: direct.Quantity, SpecName: direct.SpecName, SpecValue: direct.SpecValue,
+47
View File
@@ -0,0 +1,47 @@
package browser
import (
"testing"
)
// TestSanitize 特殊字符替换为下划线(用于 userDataDir 命名)。
func TestSanitize(t *testing.T) {
cases := map[string]string{
"acc_1": "acc_1",
"acc/1:2 3": "acc_1_2_3",
`a\b:c d`: "a_b_c_d",
"": "",
}
for in, want := range cases {
if got := sanitize(in); got != want {
t.Errorf("sanitize(%q)=%q want %q", in, got, want)
}
}
}
// TestGetCSSSelector 始终返回首选器(元素句柄仅占位,nil 与非 nil 同结果)。
func TestGetCSSSelector(t *testing.T) {
selectors := []string{"#user", "input[name=user]"}
if got := getCSSSelector(nil, selectors); got != "#user" {
t.Errorf("应返回首选器,got %q", got)
}
// 单元素切片。
if got := getCSSSelector(nil, []string{"#pwd"}); got != "#pwd" {
t.Errorf("单元素应返回该项,got %q", got)
}
}
// TestCalculateSlideDistance_Fallback nil 轨道/按钮时走兜底距离。
func TestCalculateSlideDistance_Fallback(t *testing.T) {
// 无 scratch:220-259。
dist, err := calculateSlideDistance(nil, nil, false)
if err != nil || dist < 220 || dist > 259 {
t.Fatalf("无 scratch 兜底应 220-259,got %v err=%v", dist, err)
}
// scratch:兜底 * 0.25-0.35 → 55-90。
dist, err = calculateSlideDistance(nil, nil, true)
if err != nil || dist < 55 || dist > 91 {
t.Fatalf("scratch 兜底应 55-91,got %v err=%v", dist, err)
}
}