File: httprc_test.go

package info (click to toggle)
golang-github-lestrrat-go-httprc 1.0.6-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 168 kB
  • sloc: perl: 56; sh: 6; makefile: 2
file content (112 lines) | stat: -rw-r--r-- 2,285 bytes parent folder | download
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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
package httprc_test

import (
	"context"
	"fmt"
	"net/http"
	"net/http/httptest"
	"sync"
	"testing"
	"time"

	"github.com/lestrrat-go/httprc"
	"github.com/stretchr/testify/assert"
)

type dummyErrSink struct {
	mu     sync.RWMutex
	errors []error
}

func (d *dummyErrSink) Error(err error) {
	d.mu.Lock()
	defer d.mu.Unlock()
	d.errors = append(d.errors, err)
}

func (d *dummyErrSink) getErrors() []error {
	d.mu.RLock()
	defer d.mu.RUnlock()
	return d.errors
}

func TestCache(t *testing.T) {
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()

	var muCalled sync.Mutex
	var called int
	srv := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		select {
		case <-ctx.Done():
			return
		default:
		}

		muCalled.Lock()
		called++
		muCalled.Unlock()
		w.Header().Set(`Cache-Control`, fmt.Sprintf(`max-age=%d`, 3))
		w.WriteHeader(http.StatusOK)
	}))

	errSink := &dummyErrSink{}
	c := httprc.NewCache(ctx,
		httprc.WithRefreshWindow(time.Second),
		httprc.WithErrSink(errSink),
	)

	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++ {
		v, err := c.Get(ctx, srv.URL)
		if !assert.NoError(t, err, `c.Get should succeed`) {
			return
		}
		if !assert.IsType(t, []byte(nil), v, `c.Get should return []byte`) {
			return
		}
	}
	muCalled.Lock()
	if !assert.Equal(t, 1, called, `there should only be one fetch request`) {
		return
	}
	muCalled.Unlock()

	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
		}
	}

	muCalled.Lock()
	if !assert.Equal(t, 2, called, `there should only be one fetch request`) {
		return
	}
	muCalled.Unlock()

	if !assert.True(t, len(errSink.errors) == 0) {
		return
	}

	c.Register(srv.URL,
		httprc.WithHTTPClient(srv.Client()),
		httprc.WithMinRefreshInterval(time.Second),
		httprc.WithTransformer(httprc.TransformFunc(func(_ string, _ *http.Response) (interface{}, error) {
			return nil, fmt.Errorf(`dummy error`)
		})),
	)

	_, _ = c.Get(ctx, srv.URL)
	time.Sleep(3 * time.Second)
	cancel()

	if !assert.True(t, len(errSink.getErrors()) > 0) {
		return
	}
}