30 lines
887 B
Go
30 lines
887 B
Go
package apiclient
|
|||
|
|
|
||
|
|
import (
|
||
|
|
"context"
|
||
|
|
"net/http"
|
||
|
|
"net/http/httptest"
|
||
|
|
"testing"
|
||
|
|
"time"
|
||
|
|
)
|
||
|
|
|
||
|
|
func TestDoSetsBearerOnlyWhenTokenSet(t *testing.T) {
|
||
|
|
var got []string
|
||
|
|
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||
|
|
got = append(got, r.Header.Get("Authorization"))
|
||
|
|
w.WriteHeader(http.StatusNoContent)
|
||
|
|
}))
|
||
|
|
defer ts.Close()
|
||
|
|
|
||
|
|
c := New(ts.URL, 5*time.Second)
|
||
|
|
if _, err := c.Do(context.Background(), http.MethodGet, "/x", nil, nil); err != nil {
|
||
|
|
t.Fatalf("do without token: %v", err)
|
||
|
|
}
|
||
|
|
c.Token = "secret-agent-token"
|
||
|
|
if _, err := c.Do(context.Background(), http.MethodPost, "/x", map[string]string{"a": "b"}, nil); err != nil {
|
||
|
|
t.Fatalf("do with token: %v", err)
|
||
|
|
}
|
||
|
|
if len(got) != 2 || got[0] != "" || got[1] != "Bearer secret-agent-token" {
|
||
|
|
t.Fatalf("Authorization headers = %q, want [\"\" \"Bearer secret-agent-token\"]", got)
|
||
|
|
}
|
||
|
|
}
|