golang.org/x/oauth2@v0.18.0/internal/token_test.go (about) 1 // Copyright 2014 The Go Authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style 3 // license that can be found in the LICENSE file. 4 5 package internal 6 7 import ( 8 "context" 9 "fmt" 10 "io" 11 "math" 12 "net/http" 13 "net/http/httptest" 14 "net/url" 15 "testing" 16 ) 17 18 func TestRetrieveToken_InParams(t *testing.T) { 19 styleCache := new(AuthStyleCache) 20 const clientID = "client-id" 21 ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { 22 if got, want := r.FormValue("client_id"), clientID; got != want { 23 t.Errorf("client_id = %q; want %q", got, want) 24 } 25 if got, want := r.FormValue("client_secret"), ""; got != want { 26 t.Errorf("client_secret = %q; want empty", got) 27 } 28 w.Header().Set("Content-Type", "application/json") 29 io.WriteString(w, `{"access_token": "ACCESS_TOKEN", "token_type": "bearer"}`) 30 })) 31 defer ts.Close() 32 _, err := RetrieveToken(context.Background(), clientID, "", ts.URL, url.Values{}, AuthStyleInParams, styleCache) 33 if err != nil { 34 t.Errorf("RetrieveToken = %v; want no error", err) 35 } 36 } 37 38 func TestRetrieveTokenWithContexts(t *testing.T) { 39 styleCache := new(AuthStyleCache) 40 const clientID = "client-id" 41 42 ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { 43 w.Header().Set("Content-Type", "application/json") 44 io.WriteString(w, `{"access_token": "ACCESS_TOKEN", "token_type": "bearer"}`) 45 })) 46 defer ts.Close() 47 48 _, err := RetrieveToken(context.Background(), clientID, "", ts.URL, url.Values{}, AuthStyleUnknown, styleCache) 49 if err != nil { 50 t.Errorf("RetrieveToken (with background context) = %v; want no error", err) 51 } 52 53 retrieved := make(chan struct{}) 54 cancellingts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { 55 <-retrieved 56 })) 57 defer cancellingts.Close() 58 59 ctx, cancel := context.WithCancel(context.Background()) 60 cancel() 61 _, err = RetrieveToken(ctx, clientID, "", cancellingts.URL, url.Values{}, AuthStyleUnknown, styleCache) 62 close(retrieved) 63 if err == nil { 64 t.Errorf("RetrieveToken (with cancelled context) = nil; want error") 65 } 66 } 67 68 func TestExpiresInUpperBound(t *testing.T) { 69 var e expirationTime 70 if err := e.UnmarshalJSON([]byte(fmt.Sprint(int64(math.MaxInt32) + 1))); err != nil { 71 t.Fatal(err) 72 } 73 const want = math.MaxInt32 74 if e != want { 75 t.Errorf("expiration time = %v; want %v", e, want) 76 } 77 }