This repository has been archived by the owner on Mar 8, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 15
/
roundtripper_test.go
49 lines (43 loc) · 1.58 KB
/
roundtripper_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
package httpcache_test
import (
"context"
"errors"
"fmt"
"net/http"
"net/http/httptest"
"testing"
"github.com/bxcodec/httpcache"
"github.com/bxcodec/httpcache/cache"
"github.com/bxcodec/httpcache/mocks"
"github.com/stretchr/testify/mock"
"github.com/stretchr/testify/require"
)
func TestSetToCacheRoundtrip(t *testing.T) {
mockCacheInteractor := new(mocks.ICacheInteractor)
cachedResponse := cache.CachedResponse{}
mockCacheInteractor.On("Get", mock.AnythingOfType("string")).Once().Return(cachedResponse, errors.New("uknown error"))
mockCacheInteractor.On("Set", mock.AnythingOfType("string"), mock.Anything).Once().Return(nil)
client := &http.Client{}
client.Transport = httpcache.NewCacheHandlerRoundtrip(http.DefaultTransport, true, mockCacheInteractor)
// HTTP GET 200
jsonResp := []byte(`{"message": "Hello World!"}`)
handler := func() (res http.Handler) {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
require.Equal(t, "/hello", r.RequestURI)
w.Header().Set("Content-Type", "application/json")
w.Header().Set("Cache-Control", "max-age=3600")
w.WriteHeader(http.StatusOK)
_, err := w.Write(jsonResp)
require.NoError(t, err)
})
}()
mockServer := httptest.NewServer(handler)
defer mockServer.Close()
req, err := http.NewRequestWithContext(context.Background(), http.MethodGet, fmt.Sprintf("%s/hello", mockServer.URL), http.NoBody)
require.NoError(t, err)
resp, err := client.Do(req)
require.NoError(t, err)
defer resp.Body.Close()
require.Empty(t, resp.Header.Get(httpcache.XHacheOrigin))
mockCacheInteractor.AssertExpectations(t)
}