File: cache_test.go

package info (click to toggle)
golang-github-juju-utils 0.0~git20171220.f38c0b0-5
  • links: PTS, VCS
  • area: main
  • in suites: buster
  • size: 1,748 kB
  • sloc: makefile: 20
file content (302 lines) | stat: -rw-r--r-- 8,025 bytes parent folder | download | duplicates (2)
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
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
// Copyright 2015 Canonical Ltd.
// Licensed under the LGPLv3, see LICENCE file for details.

package cache_test

import (
	"fmt"
	"sync"
	"time"

	gc "gopkg.in/check.v1"
	"gopkg.in/errgo.v1"

	"github.com/juju/utils/cache"
)

type suite struct{}

var _ = gc.Suite(&suite{})

func (*suite) TestSimpleGet(c *gc.C) {
	p := cache.New(time.Hour)
	v, err := p.Get("a", fetchValue(2))
	c.Assert(err, gc.IsNil)
	c.Assert(v, gc.Equals, 2)
}

func (*suite) TestEvict(c *gc.C) {
	p := cache.New(time.Hour)
	v, err := p.Get("a", fetchValue(2))
	c.Assert(err, gc.IsNil)
	c.Assert(v, gc.Equals, 2)

	v, err = p.Get("a", fetchValue(4))
	c.Assert(err, gc.IsNil)
	c.Assert(v, gc.Equals, 2)

	p.Evict("a")
	v, err = p.Get("a", fetchValue(3))
	c.Assert(err, gc.IsNil)
	c.Assert(v, gc.Equals, 3)

	v, err = p.Get("a", fetchValue(4))
	c.Assert(err, gc.IsNil)
	c.Assert(v, gc.Equals, 3)
}

func (*suite) TestEvictOld(c *gc.C) {
	// Test that evict removes entries even when they're
	// in the old map.

	now := time.Now()
	p := cache.New(time.Minute)

	// Populate the cache with an initial entry.
	v, err := cache.GetAtTime(p, "a", fetchValue("a"), now)
	c.Assert(err, gc.IsNil)
	c.Assert(v, gc.Equals, "a")
	c.Assert(p.Len(), gc.Equals, 1)

	v, err = cache.GetAtTime(p, "b", fetchValue("b"), now.Add(time.Minute/2))
	c.Assert(err, gc.IsNil)
	c.Assert(v, gc.Equals, "b")
	c.Assert(p.Len(), gc.Equals, 2)

	// Fetch an item after the expiry time,
	// causing current entries to be moved to old.
	v, err = cache.GetAtTime(p, "a", fetchValue("a1"), now.Add(time.Minute+1))
	c.Assert(err, gc.IsNil)
	c.Assert(v, gc.Equals, "a1")
	c.Assert(p.Len(), gc.Equals, 2)
	c.Assert(cache.OldLen(p), gc.Equals, 1)

	p.Evict("b")
	v, err = cache.GetAtTime(p, "b", fetchValue("b1"), now.Add(time.Minute+2))
	c.Assert(err, gc.IsNil)
	c.Assert(v, gc.Equals, "b1")
}

func (*suite) TestFetchError(c *gc.C) {
	p := cache.New(time.Hour)
	expectErr := errgo.New("hello")
	v, err := p.Get("a", fetchError(expectErr))
	c.Assert(err, gc.ErrorMatches, "hello")
	c.Assert(errgo.Cause(err), gc.Equals, expectErr)
	c.Assert(v, gc.Equals, nil)
}

func (*suite) TestFetchOnlyOnce(c *gc.C) {
	p := cache.New(time.Hour)
	v, err := p.Get("a", fetchValue(2))
	c.Assert(err, gc.IsNil)
	c.Assert(v, gc.Equals, 2)

	v, err = p.Get("a", fetchError(errUnexpectedFetch))
	c.Assert(err, gc.IsNil)
	c.Assert(v, gc.Equals, 2)
}

func (*suite) TestEntryExpiresAfterMaxEntryAge(c *gc.C) {
	now := time.Now()
	p := cache.New(time.Minute)
	v, err := cache.GetAtTime(p, "a", fetchValue(2), now)
	c.Assert(err, gc.IsNil)
	c.Assert(v, gc.Equals, 2)

	// Entry is definitely not expired before half the entry expiry time.
	v, err = cache.GetAtTime(p, "a", fetchError(errUnexpectedFetch), now.Add(time.Minute/2-1))
	c.Assert(err, gc.IsNil)
	c.Assert(v, gc.Equals, 2)

	// Entry is definitely expired after the entry expiry time
	v, err = cache.GetAtTime(p, "a", fetchValue(3), now.Add(time.Minute+1))
	c.Assert(v, gc.Equals, 3)
}

func (*suite) TestEntriesRemovedWhenNotRetrieved(c *gc.C) {
	now := time.Now()
	p := cache.New(time.Minute)

	// Populate the cache with an initial entry.
	v, err := cache.GetAtTime(p, "a", fetchValue("a"), now)
	c.Assert(err, gc.IsNil)
	c.Assert(v, gc.Equals, "a")
	c.Assert(p.Len(), gc.Equals, 1)

	// Fetch another item after the expiry time,
	// causing current entries to be moved to old.
	v, err = cache.GetAtTime(p, "b", fetchValue("b"), now.Add(time.Minute+1))
	c.Assert(err, gc.IsNil)
	c.Assert(v, gc.Equals, "b")
	c.Assert(p.Len(), gc.Equals, 2)
	c.Assert(cache.OldLen(p), gc.Equals, 1)

	// Fetch the other item after another expiry time
	// causing the old entries to be discarded because
	// nothing has fetched them.
	v, err = cache.GetAtTime(p, "b", fetchValue("b"), now.Add(time.Minute*2+2))
	c.Assert(err, gc.IsNil)
	c.Assert(v, gc.Equals, "b")
	c.Assert(p.Len(), gc.Equals, 1)
}

// TestRefreshedEntry tests the code path where a value is moved
// from the old map to new.
func (*suite) TestRefreshedEntry(c *gc.C) {
	now := time.Now()
	p := cache.New(time.Minute)

	// Populate the cache with an initial entry.
	v, err := cache.GetAtTime(p, "a", fetchValue("a"), now)
	c.Assert(err, gc.IsNil)
	c.Assert(v, gc.Equals, "a")
	c.Assert(p.Len(), gc.Equals, 1)

	// Fetch another item very close to the expiry time.
	v, err = cache.GetAtTime(p, "b", fetchValue("b"), now.Add(time.Minute-1))
	c.Assert(err, gc.IsNil)
	c.Assert(v, gc.Equals, "b")
	c.Assert(p.Len(), gc.Equals, 2)

	// Fetch it again just after the expiry time,
	// which should move it into the new map.
	v, err = cache.GetAtTime(p, "b", fetchError(errUnexpectedFetch), now.Add(time.Minute+1))
	c.Assert(err, gc.IsNil)
	c.Assert(v, gc.Equals, "b")
	c.Assert(p.Len(), gc.Equals, 2)

	// Fetch another item, causing "a" to be removed from the cache
	// and keeping "b" in there.
	v, err = cache.GetAtTime(p, "c", fetchValue("c"), now.Add(time.Minute*2+2))
	c.Assert(err, gc.IsNil)
	c.Assert(v, gc.Equals, "c")
	c.Assert(p.Len(), gc.Equals, 2)
}

// TestConcurrentFetch checks that the cache is safe
// to use concurrently. It is designed to fail when
// tested with the race detector enabled.
func (*suite) TestConcurrentFetch(c *gc.C) {
	p := cache.New(time.Minute)
	var wg sync.WaitGroup
	wg.Add(1)
	go func() {
		defer wg.Done()
		v, err := p.Get("a", fetchValue("a"))
		c.Check(err, gc.IsNil)
		c.Check(v, gc.Equals, "a")
	}()
	wg.Add(1)
	go func() {
		defer wg.Done()
		v, err := p.Get("b", fetchValue("b"))
		c.Check(err, gc.IsNil)
		c.Check(v, gc.Equals, "b")
	}()
	wg.Wait()
}

func (*suite) TestRefreshSpread(c *gc.C) {
	now := time.Now()
	p := cache.New(time.Minute)
	// Get all values to start with.
	const N = 100
	for i := 0; i < N; i++ {
		v, err := cache.GetAtTime(p, fmt.Sprint(i), fetchValue(i), now)
		c.Assert(err, gc.IsNil)
		c.Assert(v, gc.Equals, i)
	}
	counts := make([]int, time.Minute/time.Millisecond/10+1)

	// Continually get values over the course of the
	// expiry time; the fetches should be spread out.
	slot := 0
	for t := now.Add(0); t.Before(now.Add(time.Minute + 1)); t = t.Add(time.Millisecond * 10) {
		for i := 0; i < N; i++ {
			cache.GetAtTime(p, fmt.Sprint(i), func() (interface{}, error) {
				counts[slot]++
				return i, nil
			}, t)
		}
		slot++
	}

	// There should be no fetches in the first half of the cycle.
	for i := 0; i < len(counts)/2; i++ {
		c.Assert(counts[i], gc.Equals, 0, gc.Commentf("slot %d", i))
	}

	max := 0
	total := 0
	for _, count := range counts {
		if count > max {
			max = count
		}
		total += count
	}
	if max > 10 {
		c.Errorf("requests grouped too closely (max %d)", max)
	}
	c.Assert(total, gc.Equals, N)
}

func (*suite) TestSingleFlight(c *gc.C) {
	p := cache.New(time.Minute)
	start := make(chan struct{})
	var wg sync.WaitGroup

	wg.Add(1)
	go func() {
		defer wg.Done()
		x, err := p.Get("x", func() (interface{}, error) {
			start <- struct{}{}
			<-start
			return 99, nil
		})
		c.Check(x, gc.Equals, 99)
		c.Check(err, gc.Equals, nil)

	}()
	// Wait for the fetch to start.
	<-start
	wg.Add(1)
	go func() {
		defer wg.Done()
		x, err := p.Get("x", func() (interface{}, error) {
			c.Errorf("fetch function unexpectedly called with inflight request")
			return 55, nil
		})
		c.Check(x, gc.Equals, 99)
		c.Check(err, gc.Equals, nil)
	}()

	// Check that we can still get other values while the
	// other fetches are in progress.
	y, err := p.Get("y", func() (interface{}, error) {
		return 88, nil
	})
	c.Check(y, gc.Equals, 88)
	c.Check(err, gc.Equals, nil)

	// Let the original fetch proceed, which should let the other one
	// succeed too, but sleep for a little bit to let the second goroutine
	// actually initiate its request.
	time.Sleep(time.Millisecond)
	start <- struct{}{}
	wg.Wait()
}

var errUnexpectedFetch = errgo.New("fetch called unexpectedly")

func fetchError(err error) func() (interface{}, error) {
	return func() (interface{}, error) {
		return nil, err
	}
}

func fetchValue(val interface{}) func() (interface{}, error) {
	return func() (interface{}, error) {
		return val, nil
	}
}