-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathhttprc_test.go
61 lines (52 loc) · 1.25 KB
/
httprc_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
package httprc_test
import (
"context"
"fmt"
"net/http"
"net/http/httptest"
"testing"
"time"
"github.com/lestrrat-go/httprc"
"github.com/stretchr/testify/assert"
)
func TestCache(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
var called int
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
select {
case <-ctx.Done():
return
default:
}
t.Logf("HTTP handler")
called++
w.Header().Set(`Cache-Control`, fmt.Sprintf(`max-age=%d`, 3))
w.WriteHeader(http.StatusOK)
}))
c := httprc.New(ctx, httprc.WithRefreshWindow(time.Second))
c.Register(srv.URL, httprc.WithHTTPClient(srv.Client()), httprc.WithMinRefreshInterval(time.Second))
if !assert.True(t, c.IsRegistered(srv.URL)) {
return
}
for i := 0; i < 3; i++ {
_, err := c.Get(ctx, srv.URL)
if !assert.NoError(t, err, `c.Get should succeed`) {
return
}
}
if !assert.Equal(t, 1, called, `there should only be one fetch request`) {
return
}
time.Sleep(4 * time.Second)
for i := 0; i < 3; i++ {
_, err := c.Get(ctx, srv.URL)
if !assert.NoError(t, err, `c.Get should succeed`) {
return
}
}
if !assert.Equal(t, 2, called, `there should only be one fetch request`) {
return
}
cancel()
}