-
Notifications
You must be signed in to change notification settings - Fork 0
/
transport_test.go
82 lines (66 loc) · 2.02 KB
/
transport_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
package oauth2utils_test
import (
"context"
"io/ioutil"
"net/http"
"net/http/httptest"
"time"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
"golang.org/x/oauth2"
. "github.com/koofr/go-oauth2utils"
)
var _ = Describe("Transport", func() {
It("add the access token to the request", func() {
var expectedAccessToken string
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
go GinkgoRecover()
Expect(r.Header.Get("Authorization")).To(Equal("Bearer " + expectedAccessToken))
w.Write([]byte("resp"))
}))
defer server.Close()
token := &oauth2.Token{
AccessToken: "a1",
RefreshToken: "r1",
Expiry: time.Now().Add(15 * time.Minute),
}
onUpdateCalled := false
reqCtx := context.WithValue(context.Background(), "foo", "bar")
onUpdate := func(ctx context.Context, t *oauth2.Token) {
Expect(ctx).To(Equal(reqCtx))
onUpdateCalled = true
}
tokenSourceFactory := func(ctx context.Context, t *oauth2.Token) oauth2.TokenSource {
Expect(ctx).To(Equal(reqCtx))
return &TestTokenSource{}
}
s := NewReactiveTokenSource(tokenSourceFactory, token, onUpdate)
client := &http.Client{
Transport: &Transport{
Base: server.Client().Transport,
Source: s,
},
}
expectedAccessToken = token.AccessToken
req, err := http.NewRequest("GET", server.URL, nil)
Expect(err).NotTo(HaveOccurred())
req = req.WithContext(reqCtx)
res, err := client.Do(req)
Expect(err).NotTo(HaveOccurred())
body, err := ioutil.ReadAll(res.Body)
res.Body.Close()
Expect(body).To(Equal([]byte("resp")))
Expect(onUpdateCalled).To(BeFalse())
token.Expiry = time.Now().Add(-15 * time.Minute)
expectedAccessToken = "a2"
req, err = http.NewRequest("GET", server.URL, nil)
Expect(err).NotTo(HaveOccurred())
req = req.WithContext(reqCtx)
res, err = client.Do(req)
Expect(err).NotTo(HaveOccurred())
body, err = ioutil.ReadAll(res.Body)
res.Body.Close()
Expect(body).To(Equal([]byte("resp")))
Expect(onUpdateCalled).To(BeTrue())
})
})