package seckill import ( "fmt" "net/http" "net/http/httptest" "strings" "sync" "sync/atomic" "testing" "time" "douyu_go/internal/activity" "douyu_go/internal/client" "douyu_go/internal/trace" "douyu_go/internal/types" ) func TestSeckillDrillUsesReadOnlyAccountChecks(t *testing.T) { var limitCalls int server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/json") switch r.URL.Path { case "/bind": fmt.Fprint(w, `{"error":0,"data":{"gameRole":{"roleName":"测试角色"}}}`) case "/limit": limitCalls++ fmt.Fprint(w, `{"error":0,"data":{"limit":"1"}}`) default: http.NotFound(w, r) } })) defer server.Close() act := *activity.Get("peace") act.BaseURL = server.URL act.BindInfoURL = server.URL + "/bind" act.BatchLimitURL = server.URL + "/limit" base := client.New(&act, server.URL+"/time", &trace.Recorder{}, "") paths := writeAccountFile(t, "a") scheduler := New(base, paths, nil, 8, 1, nil, types.SeckillModeAggressive) scheduler.LoadAccounts() scheduler.UpdateProducts([]types.Product{{ CommodityID: "goods-1", CommodityName: "测试商品", }}) status, err := scheduler.startSeckillDrill(map[string]string{"a": "goods-1"}, 120*time.Millisecond) if err != nil { t.Fatal(err) } if !status.Active || status.TotalAccounts != 1 { t.Fatalf("unexpected initial drill status: %+v", status) } deadline := time.Now().Add(3 * time.Second) for time.Now().Before(deadline) { status = scheduler.GetSeckillDrillStatus() if !status.Active { break } time.Sleep(20 * time.Millisecond) } if status.Active || status.State != "completed" { t.Fatalf("unexpected final drill status: %+v", status) } if status.SuccessAccounts != 1 || status.FailedAccounts != 0 { t.Fatalf("unexpected drill counts: %+v", status) } if limitCalls != 1 { t.Fatalf("limitCalls=%d, want 1", limitCalls) } } func TestSeckillDrillSwitchesActivityHotProxyBeforeStart(t *testing.T) { hotProxy := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/json") if r.URL.Path == "/limit" { fmt.Fprint(w, `{"error":1644400007,"msg":"活动火爆,请稍后再试"}`) return } fmt.Fprint(w, `{"error":0,"data":{"gameRole":{"roleName":"热门代理角色"}}}`) })) defer hotProxy.Close() safeProxy := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/json") switch r.URL.Path { case "/limit": fmt.Fprint(w, `{"error":0,"data":{"limit":"1"}}`) case "/bind": fmt.Fprint(w, `{"error":0,"data":{"gameRole":{"roleName":"备用代理角色"}}}`) default: http.NotFound(w, r) } })) defer safeProxy.Close() act := *activity.Get("peace") act.BindInfoURL = "http://douyu.test/bind" act.BatchLimitURL = "http://douyu.test/limit" base := client.New(&act, "http://douyu.test/time", &trace.Recorder{}, "") paths := writeAccountFile(t, "a") scheduler := New(base, paths, nil, 8, 1, nil, types.SeckillModeAggressive) scheduler.LoadAccounts() scheduler.UpdateProducts([]types.Product{{ CommodityID: "goods-1", CommodityName: "测试商品", }}) scheduler.UpdateProxySettings(types.Config{ ProxyEnabled: true, ProxyRequired: true, AccountsPerProxy: 1, ProxySparePercent: 50, }) hotClient, err := client.NewWithProxy(&act, "http://douyu.test/time", &trace.Recorder{}, hotProxy.URL) if err != nil { t.Fatal(err) } safeClient, err := client.NewWithProxy(&act, "http://douyu.test/time", &trace.Recorder{}, safeProxy.URL) if err != nil { t.Fatal(err) } group := &proxyRuntimeGroup{ groupIndex: 1, accountNames: []string{"a"}, activeURL: hotProxy.URL, activeIP: "1.1.1.1", } scheduler.replaceAccountClients(preparedProxyPool{ accountClients: map[string]*client.DouyuClient{"a": hotClient}, activeClients: []*client.DouyuClient{hotClient}, groups: map[*client.DouyuClient]*proxyRuntimeGroup{hotClient: group}, standbys: []validatedProxy{{ url: safeProxy.URL, client: safeClient, ip: "2.2.2.2", }}, allClients: []*client.DouyuClient{hotClient, safeClient}, standbyTarget: 1, }) status, err := scheduler.startSeckillDrill(map[string]string{"a": "goods-1"}, 120*time.Millisecond) if err != nil { t.Fatal(err) } if !status.Active { t.Fatalf("unexpected initial drill status: %+v", status) } if scheduler.clientForAccount("a") != safeClient { t.Fatal("drill preparation should switch activity-hot proxy to standby") } deadline := time.Now().Add(3 * time.Second) for time.Now().Before(deadline) { status = scheduler.GetSeckillDrillStatus() if !status.Active { break } time.Sleep(20 * time.Millisecond) } if status.Active || status.State != "completed" || status.FailedAccounts != 0 { t.Fatalf("unexpected final drill status: %+v", status) } } func TestSeckillDrillDoesNotWaitForSlowWarmup(t *testing.T) { roleStarted := make(chan struct{}, 1) roleRelease := make(chan struct{}) var releaseOnce sync.Once releaseRole := func() { releaseOnce.Do(func() { close(roleRelease) }) } var limitCalls atomic.Int32 server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/json") switch r.URL.Path { case "/bind": select { case roleStarted <- struct{}{}: default: } <-roleRelease fmt.Fprint(w, `{"error":0,"data":{"gameRole":{"roleName":"慢角色"}}}`) case "/limit": limitCalls.Add(1) fmt.Fprint(w, `{"error":0,"data":{"limit":"1"}}`) default: http.NotFound(w, r) } })) defer server.Close() defer releaseRole() act := *activity.Get("peace") act.BindInfoURL = server.URL + "/bind" act.BatchLimitURL = server.URL + "/limit" base := client.New(&act, server.URL+"/time", &trace.Recorder{}, "") paths := writeAccountFile(t, "a") scheduler := New(base, paths, nil, 8, 1, nil, types.SeckillModeAggressive) scheduler.LoadAccounts() scheduler.UpdateProducts([]types.Product{{ CommodityID: "goods-1", CommodityName: "测试商品", }}) if _, err := scheduler.startSeckillDrill( map[string]string{"a": "goods-1"}, 120*time.Millisecond, ); err != nil { t.Fatal(err) } select { case <-roleStarted: case <-time.After(time.Second): t.Fatal("slow warmup did not start") } deadline := time.Now().Add(800 * time.Millisecond) for time.Now().Before(deadline) { status := scheduler.GetSeckillDrillStatus() if !status.Active { if status.State != "completed" || status.SuccessAccounts != 1 { t.Fatalf("unexpected drill status while warmup blocked: %+v", status) } if got := limitCalls.Load(); got != 1 { t.Fatalf("T0 batch limit calls=%d, want 1", got) } return } time.Sleep(10 * time.Millisecond) } t.Fatal("drill T0 waited for slow warmup role lookup") } func TestFinishSeckillDrillKeepsAlreadyCancelledState(t *testing.T) { scheduler := &Scheduler{ drillStatus: types.SeckillDrillStatus{ State: "cancelled", Message: "抢购预演已取消", }, } scheduler.finishSeckillDrill("completed", "不应覆盖") status := scheduler.GetSeckillDrillStatus() if status.State != "cancelled" || status.Message != "抢购预演已取消" { t.Fatalf("unexpected status after duplicate finish: %+v", status) } } func TestSeckillDrillStopsWhenRealRunStarts(t *testing.T) { act := *activity.Get("peace") base := client.New(&act, "http://douyu.test/time", &trace.Recorder{}, "") paths := writeAccountFile(t, "a") scheduler := New(base, paths, nil, 8, 1, nil, types.SeckillModeAggressive) scheduler.LoadAccounts() scheduler.UpdateProducts([]types.Product{{ CommodityID: "goods-1", CommodityName: "测试商品", }}) if _, err := scheduler.startSeckillDrill(map[string]string{"a": "goods-1"}, 300*time.Millisecond); err != nil { t.Fatal(err) } if !scheduler.TryStartRun() { t.Fatal("real run should start") } defer scheduler.finishRun() deadline := time.Now().Add(2 * time.Second) for time.Now().Before(deadline) { status := scheduler.GetSeckillDrillStatus() if !status.Active { if status.State != "failed" || !strings.Contains(status.Message, "真实抢购已启动") { t.Fatalf("unexpected drill status: %+v", status) } return } time.Sleep(20 * time.Millisecond) } t.Fatal("drill did not stop after real run started") }