feat: 完善代理池与抢购链路,发布 0.5.0
This commit is contained in:
@@ -0,0 +1,79 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"douyu_go/internal/types"
|
||||
)
|
||||
|
||||
func TestProxyNeedsStartupRefresh(t *testing.T) {
|
||||
now := time.Date(2026, 11, 20, 0, 30, 0, 0, time.Local)
|
||||
base := types.Config{
|
||||
ProxyEnabled: true,
|
||||
ProxyAPI: "https://service.ipzan.com/core-extract",
|
||||
ProxyExpiresAt: now.Add(10 * time.Minute).UnixMilli(),
|
||||
}
|
||||
if proxyNeedsStartupRefresh(base, now) {
|
||||
t.Fatal("未过期代理不应在启动时刷新")
|
||||
}
|
||||
base.ProxyExpiresAt = now.Add(20 * time.Second).UnixMilli()
|
||||
if !proxyNeedsStartupRefresh(base, now) {
|
||||
t.Fatal("距离过期不足30秒时应提前刷新")
|
||||
}
|
||||
base.ProxyEnabled = false
|
||||
if proxyNeedsStartupRefresh(base, now) {
|
||||
t.Fatal("代理未启用时不应刷新")
|
||||
}
|
||||
}
|
||||
|
||||
func TestIsStartupProxyFailure(t *testing.T) {
|
||||
cases := []struct {
|
||||
err error
|
||||
want bool
|
||||
}{
|
||||
{err: errors.New(`Get "https://www.douyu.com": Proxy Authentication Required`), want: true},
|
||||
{err: errors.New("proxyconnect tcp: connection refused"), want: true},
|
||||
{err: errors.New("Get https://www.douyu.com: unexpected EOF"), want: true},
|
||||
{err: errors.New("context deadline exceeded"), want: true},
|
||||
{err: errors.New("业务接口返回库存不足"), want: false},
|
||||
{err: nil, want: false},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
if got := isStartupProxyFailure(tc.err); got != tc.want {
|
||||
t.Errorf("isStartupProxyFailure(%v)=%v, want %v", tc.err, got, tc.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestRefreshStartupProxyValidatesAndUpdatesConfig(t *testing.T) {
|
||||
proxyServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.URL.Host == "myip.ipip.net" {
|
||||
fmt.Fprint(w, "当前 IP:127.0.0.1 来自于:中国 测试")
|
||||
return
|
||||
}
|
||||
http.Error(w, "unexpected request", http.StatusBadGateway)
|
||||
}))
|
||||
defer proxyServer.Close()
|
||||
|
||||
apiServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
fmt.Fprint(w, proxyServer.URL)
|
||||
}))
|
||||
defer apiServer.Close()
|
||||
|
||||
cfg := types.Config{
|
||||
ProxyEnabled: true,
|
||||
ProxyAPI: apiServer.URL,
|
||||
}
|
||||
app := &App{}
|
||||
if err := app.refreshStartupProxy(&cfg, "测试"); err != nil {
|
||||
t.Fatalf("refreshStartupProxy() error = %v", err)
|
||||
}
|
||||
if cfg.ProxyURL != proxyServer.URL {
|
||||
t.Fatalf("ProxyURL=%q, want %q", cfg.ProxyURL, proxyServer.URL)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user