gitlink-cli/internal/client/client_test.go

53 lines
1.6 KiB
Go

package client
import (
"net/http"
"net/http/httptest"
"testing"
)
func TestNormalizeAPIPathStripsDuplicateAPIPrefix(t *testing.T) {
got := normalizeAPIPath("https://www.gitlink.org.cn/api", "/api/v1/repos/Gitlink/gitlink-cli/contents/README.md")
want := "/v1/repos/Gitlink/gitlink-cli/contents/README.md"
if got != want {
t.Fatalf("normalizeAPIPath() = %q, want %q", got, want)
}
}
func TestNormalizeAPIPathKeepsRegularPath(t *testing.T) {
got := normalizeAPIPath("https://www.gitlink.org.cn/api", "/projects")
want := "/projects"
if got != want {
t.Fatalf("normalizeAPIPath() = %q, want %q", got, want)
}
}
func TestNormalizeAPIPathKeepsAPIPrefixForNonAPIBaseURL(t *testing.T) {
got := normalizeAPIPath("https://www.gitlink.org.cn", "/api/v1/repos/Gitlink/gitlink-cli")
want := "/api/v1/repos/Gitlink/gitlink-cli"
if got != want {
t.Fatalf("normalizeAPIPath() = %q, want %q", got, want)
}
}
func TestDoWithHeadersAddsRequestHeaders(t *testing.T) {
var gotHeader string
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
gotHeader = r.Header.Get("X-Test")
w.Header().Set("Content-Type", "application/json")
w.Write([]byte(`{"status":1,"data":{"ok":true}}`))
}))
defer server.Close()
cli := &Client{HTTP: server.Client(), BaseURL: server.URL}
headers := http.Header{}
headers.Set("X-Test", "value")
if _, err := cli.DoWithHeaders("GET", "/users/me", nil, nil, headers); err != nil {
t.Fatalf("DoWithHeaders returned error: %v", err)
}
if gotHeader != "value" {
t.Fatalf("X-Test header = %q, want value", gotHeader)
}
}