oauth2/transport_test.go

68 строки
1.7 KiB
Go
Исходник Обычный вид История

2014-06-17 19:22:06 +04:00
package oauth2
import (
"net/http"
"net/http/httptest"
"testing"
"time"
)
type mockTokenFetcher struct{ token *Token }
func (f *mockTokenFetcher) FetchToken(existing *Token) (*Token, error) {
return f.token, nil
}
func TestInitialTokenRead(t *testing.T) {
tr := NewAuthorizedTransport(http.DefaultTransport, nil, &Token{AccessToken: "abc"})
2014-06-17 19:22:06 +04:00
server := newMockServer(func(w http.ResponseWriter, r *http.Request) {
if r.Header.Get("Authorization") != "Bearer abc" {
2014-07-09 09:27:34 +04:00
t.Errorf("Transport doesn't set the Authorization header from the initial token")
2014-06-17 19:22:06 +04:00
}
})
defer server.Close()
client := http.Client{Transport: tr}
client.Get(server.URL)
}
2014-07-09 09:27:34 +04:00
func TestTokenFetch(t *testing.T) {
2014-06-17 19:22:06 +04:00
fetcher := &mockTokenFetcher{
token: &Token{
AccessToken: "abc",
},
}
tr := NewAuthorizedTransport(http.DefaultTransport, fetcher, nil)
2014-06-17 19:22:06 +04:00
server := newMockServer(func(w http.ResponseWriter, r *http.Request) {
if r.Header.Get("Authorization") != "Bearer abc" {
2014-07-09 09:27:34 +04:00
t.Errorf("Transport doesn't set the Authorization header from the fetched token")
2014-06-17 19:22:06 +04:00
}
})
defer server.Close()
client := http.Client{Transport: tr}
client.Get(server.URL)
2014-07-09 09:27:34 +04:00
if tr.Token().AccessToken != "abc" {
t.Errorf("New token is not set, found %v", tr.Token())
2014-06-17 19:22:06 +04:00
}
}
func TestExpiredWithNoAccessToken(t *testing.T) {
token := &Token{}
if !token.Expired() {
2014-06-23 02:07:44 +04:00
t.Errorf("Token should be expired if no access token is provided")
2014-06-17 19:22:06 +04:00
}
}
func TestExpiredWithExpiry(t *testing.T) {
token := &Token{
Expiry: time.Now().Add(-5 * time.Hour),
}
if !token.Expired() {
2014-06-23 02:07:44 +04:00
t.Errorf("Token should be expired if no access token is provided")
2014-06-17 19:22:06 +04:00
}
}
func newMockServer(handler func(w http.ResponseWriter, r *http.Request)) *httptest.Server {
return httptest.NewServer(http.HandlerFunc(handler))
}