53 lines
1.3 KiB
Go
53 lines
1.3 KiB
Go
package client
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"net/http"
|
|
"testing"
|
|
)
|
|
|
|
type roundTripFunc func(*http.Request) (*http.Response, error)
|
|
|
|
func (f roundTripFunc) RoundTrip(req *http.Request) (*http.Response, error) {
|
|
return f(req)
|
|
}
|
|
|
|
func TestIsProxyTransportFailure(t *testing.T) {
|
|
if IsProxyTransportFailure(nil) {
|
|
t.Fatal("nil error should not be treated as proxy failure")
|
|
}
|
|
if IsProxyTransportFailure(context.Canceled) {
|
|
t.Fatal("context cancellation should not trigger proxy failover")
|
|
}
|
|
if !IsProxyTransportFailure(errors.New("connection reset by peer")) {
|
|
t.Fatal("transport error should trigger proxy failover")
|
|
}
|
|
}
|
|
|
|
func TestMonitorProxyHealthReportsRoundTripFailure(t *testing.T) {
|
|
wantErr := errors.New("proxy connection refused")
|
|
cli := &DouyuClient{
|
|
HTTPClient: &http.Client{
|
|
Transport: roundTripFunc(func(*http.Request) (*http.Response, error) {
|
|
return nil, wantErr
|
|
}),
|
|
},
|
|
}
|
|
var gotErr error
|
|
MonitorProxyHealth(cli, func(err error) {
|
|
gotErr = err
|
|
})
|
|
|
|
req, err := http.NewRequest(http.MethodGet, "https://example.test", nil)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if _, err := cli.HTTPClient.Do(req); !errors.Is(err, wantErr) {
|
|
t.Fatalf("HTTPClient.Do() error=%v, want %v", err, wantErr)
|
|
}
|
|
if !errors.Is(gotErr, wantErr) {
|
|
t.Fatalf("health handler error=%v, want %v", gotErr, wantErr)
|
|
}
|
|
}
|