friendica-exporter/internal/client/client_test.go

98 lines
2 KiB
Go
Raw Normal View History

2024-10-24 20:26:41 +02:00
package client
import (
"errors"
"fmt"
"net/http"
"net/http/httptest"
"testing"
"time"
"friendica-exporter/internal/testutil"
"friendica-exporter/serverinfo"
"github.com/google/go-cmp/cmp"
)
func TestClient(t *testing.T) {
wantUserAgent := "test-ua"
tt := []struct {
desc string
handler func(t *testing.T) http.Handler
wantInfo *serverinfo.ServerInfo
wantErr error
}{
{
desc: "statstoken",
handler: func(t *testing.T) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
fmt.Fprintln(w, "{}")
})
},
wantInfo: &serverinfo.ServerInfo{},
wantErr: nil,
},
{
desc: "user-agent",
handler: func(t *testing.T) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
ua := req.UserAgent()
if ua != wantUserAgent {
t.Errorf("got user-agent %q, want %q", ua, wantUserAgent)
}
fmt.Fprintln(w, "{}")
})
},
wantInfo: &serverinfo.ServerInfo{},
wantErr: nil,
},
{
desc: "parse error",
handler: func(t *testing.T) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
w.WriteHeader(http.StatusOK)
})
},
wantInfo: nil,
wantErr: errors.New("can not parse server info: EOF"),
},
{
desc: "ratelimit",
handler: func(t *testing.T) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
w.WriteHeader(http.StatusTooManyRequests)
})
},
wantErr: ErrRatelimit,
},
}
for _, tc := range tt {
tc := tc
t.Run(tc.desc, func(t *testing.T) {
t.Parallel()
s := httptest.NewServer(tc.handler(t))
defer s.Close()
client := New(s.URL, time.Second, wantUserAgent, false)
info, err := client()
if !testutil.EqualErrorMessage(err, tc.wantErr) {
t.Errorf("got error %q, want %q", err, tc.wantErr)
}
if err != nil {
return
}
if diff := cmp.Diff(info, tc.wantInfo); diff != "" {
t.Errorf("info differs: -got+want\n%s", diff)
}
})
}
}