package client import ( "fmt" "net/http" "net/http/httptest" "testing" ) func TestParseProxyURL(t *testing.T) { tests := []struct { input string expectURL string expectError bool }{ {"", "", false}, {" ", "", false}, {"127.0.0.1:8888", "http://127.0.0.1:8888", false}, {"http://127.0.0.1:8888", "http://127.0.0.1:8888", false}, {"https://127.0.0.1:8888", "https://127.0.0.1:8888", false}, {"socks5://127.0.0.1:1080", "socks5://127.0.0.1:1080", false}, {"http://user:pass@127.0.0.1:8888", "http://user:pass@127.0.0.1:8888", false}, {"ftp://127.0.0.1:21", "", true}, } for _, tc := range tests { u, err := ParseProxyURL(tc.input) if tc.expectError { if err == nil { t.Fatalf("ParseProxyURL(%q) expected error, got nil", tc.input) } } else { if err != nil { t.Fatalf("ParseProxyURL(%q) unexpected error: %v", tc.input, err) } if tc.expectURL == "" { if u != nil { t.Fatalf("ParseProxyURL(%q) expected nil, got %v", tc.input, u) } } else if u.String() != tc.expectURL { t.Fatalf("ParseProxyURL(%q) = %q, want %q", tc.input, u.String(), tc.expectURL) } } } } func TestFetchProxyFromAPI_XKDaili(t *testing.T) { // 模拟星空代理正常返回 ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/json; charset=utf-8") fmt.Fprint(w, `{ "status":100 ,"info":"成功" , "data": [{"ip": "115.230.134.174", "port": "40014", "prov": "浙江", "city": "嘉兴"}]}`) })) defer ts.Close() res, err := FetchProxyFromAPI(ts.URL) if err != nil { t.Fatalf("FetchProxyFromAPI failed: %v", err) } if res.IP != "115.230.134.174" || res.Port != "40014" { t.Fatalf("unexpected res: %+v", res) } if res.ProxyURL != "http://115.230.134.174:40014" { t.Fatalf("unexpected proxy url: %s", res.ProxyURL) } if res.Region != "浙江 嘉兴" { t.Fatalf("unexpected region: %s", res.Region) } } func TestFetchProxyFromAPI_Error(t *testing.T) { // 模拟星空代理未加白名单报错 ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/json; charset=utf-8") fmt.Fprint(w, `{ "status":211 , "info":"当前IP不在白名单内" }`) })) defer ts.Close() _, err := FetchProxyFromAPI(ts.URL) if err == nil { t.Fatal("expected error, got nil") } if err.Error() != "代理平台返回: 当前IP不在白名单内 (状态码=211)" { t.Fatalf("unexpected error string: %v", err) } } func TestFetchProxyFromAPI_Text(t *testing.T) { // 模拟纯文本返回 ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { fmt.Fprint(w, "221.122.91.45:3128\r\n") })) defer ts.Close() res, err := FetchProxyFromAPI(ts.URL) if err != nil { t.Fatalf("FetchProxyFromAPI failed: %v", err) } if res.ProxyURL != "http://221.122.91.45:3128" { t.Fatalf("unexpected proxy url: %s", res.ProxyURL) } }