forked from evcc-io/evcc
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcache_test.go
130 lines (108 loc) Β· 2.14 KB
/
cache_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
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
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
package provider
import (
"errors"
"testing"
"time"
"github.com/benbjohnson/clock"
"github.com/evcc-io/evcc/api"
"github.com/stretchr/testify/assert"
)
func TestCachedGetter(t *testing.T) {
var idx int
cases := []struct {
f float64
e error
}{
{f: 1, e: nil},
{f: 2, e: nil},
{f: 3, e: errors.New("3")},
}
g := func() (float64, error) {
f := cases[idx].f
e := cases[idx].e
idx++
return f, e
}
duration := time.Second
c := ResettableCached(g, duration)
clock := clock.NewMock()
c.clock = clock
expect := func(s struct {
f float64
e error
},
) {
f, e := c.Get()
if f != s.f || e != s.e {
t.Errorf("unexpected cache value: %f, %v\n", f, e)
}
}
expect(cases[0])
expect(cases[0])
clock.Add(2 * duration)
expect(cases[1])
clock.Add(2 * duration)
expect(cases[2])
}
func TestCacheReset(t *testing.T) {
var i int64
g := func() (int64, error) {
i++
return i, nil
}
c := ResettableCached(g, 10*time.Minute)
clock := clock.NewMock()
c.clock = clock
test := func(exp int64) {
v, _ := c.Get()
if exp != v {
t.Errorf("expected %d, got %d", exp, v)
}
}
test(1)
test(1)
c.Reset()
test(2)
test(2)
clock.Add(10*time.Minute + 1)
test(3)
}
func TestRetryWithBackoff(t *testing.T) {
tests := []struct {
deltaTime time.Duration
returnError bool
functionCalled bool
}{
{0 * time.Second, true, true},
{4 * time.Second, true, false},
{6 * time.Second, true, true},
{9 * time.Second, true, false},
{11 * time.Second, true, true},
{14 * time.Second, true, false},
{16 * time.Second, false, true},
{16 * time.Minute, true, true},
{4 * time.Second, true, false},
{6 * time.Second, true, true},
}
var returnError, functionCalled bool
g := func() (int64, error) {
functionCalled = true
if returnError {
return 1, api.ErrTimeout
}
return 1, nil
}
c := ResettableCached(g, 15*time.Minute)
clock := clock.NewMock()
c.clock = clock
for _, tt := range tests {
functionCalled = false
returnError = tt.returnError
clock.Add(tt.deltaTime)
_, err := c.Get()
if returnError {
assert.Error(t, err)
}
assert.Equal(t, tt.functionCalled, functionCalled)
}
}