-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathring_test.go
77 lines (70 loc) · 1.85 KB
/
ring_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
package ring
import (
"fmt"
"testing"
"time"
"github.com/stretchr/testify/assert"
)
const (
cyclePerMinute = 6
minutesToCache = 4
reducedMinutesToCache = 2
cycleCount = minutesToCache * cyclePerMinute
)
func Test_RingEvictsOldValues(t *testing.T) {
// deliberate keep look back cache to smaller than needed and ensure
// all values are new and old ones are evicted.
ch := NewRingChannel(reducedMinutesToCache * cyclePerMinute)
assert.Equal(t, 0, ch.Len())
for cycle := 1; cycle <= cycleCount; cycle++ {
ch.In() <- cycle
// let channel pass messages
time.Sleep(1 * time.Millisecond)
if cycle%cyclePerMinute == 0 {
// 1 minute cycle over, lets consume it.
consumer := consume(ch)
// ensure we consumed exactly cyclePerMinute = 6
assert.Equal(t, cyclePerMinute, len(consumer))
// enusre the first value is fresh and newer or equal to cycle number.
// this also means old values are evicted out.
assert.GreaterOrEqual(t, cycle, consumer[0])
}
}
ch.Close()
consume(ch)
assert.Equal(t, 0, ch.Len())
}
func Test_ReCycleRing(t *testing.T) {
ch := NewRingChannel(cycleCount)
for cycle := 1; cycle <= cycleCount; cycle++ {
ch.In() <- cycle
// let channel pass messages
time.Sleep(1 * time.Millisecond)
if cycle%cyclePerMinute == 0 {
// 1 minute cycle over, lets consume it.
post := consume(ch)
// fake that metrics post failed, so put back cycles back into the ring.
for _, putBack := range post {
ch.In() <- putBack
}
}
}
assert.Equal(t, cycleCount, ch.Len())
ch.Close()
consume(ch)
assert.Equal(t, 0, ch.Len())
}
func consume(ch *RingChannel) []int {
var consumer []int
for i := 0; i <= cycleCount; i++ {
select {
case x := <-ch.Out():
consumer = append(consumer, x.(int))
default:
// nothing available
break
}
}
fmt.Printf("%v\n", consumer)
return consumer
}