-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlistener_test.go
More file actions
78 lines (68 loc) · 1.64 KB
/
listener_test.go
File metadata and controls
78 lines (68 loc) · 1.64 KB
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
package cbytecache
import (
"bytes"
"fmt"
"strconv"
"sync/atomic"
"testing"
"time"
"github.com/koykov/clock"
"github.com/koykov/hash/fnv"
)
type countListener struct {
k, n, b, c uint32
}
func (l *countListener) Listen(entry Entry) error {
key, body := entry.Key, entry.Body
if len(key) < 3 || key[:3] != "key" {
atomic.AddUint32(&l.k, 1)
return fmt.Errorf("corrupted key: %s", key)
}
raw := key[3:]
n, err := strconv.Atoi(raw)
if err != nil {
atomic.AddUint32(&l.n, 1)
return err
}
expect := getEntryBody(n)
if !bytes.Equal(expect, body) {
atomic.AddUint32(&l.b, 1)
return fmt.Errorf("mismatch body and expactation")
}
atomic.AddUint32(&l.c, 1)
return nil
}
func (l *countListener) stats() (uint32, uint32, uint32, uint32) {
return atomic.LoadUint32(&l.k), atomic.LoadUint32(&l.n), atomic.LoadUint32(&l.b), atomic.LoadUint32(&l.c)
}
func TestListener(t *testing.T) {
t.Run("count", func(t *testing.T) {
const count = 1000
var l countListener
conf := DefaultConfig(time.Minute, &fnv.Hasher{}, 0)
conf.Clock = clock.NewClock()
conf.ExpireListener = &l
cache, err := New(conf)
if err != nil {
t.Fatal(err)
}
for i := 0; i < count; i++ {
key := fmt.Sprintf("key%d", i)
if err = cache.Set(key, getEntryBody(i)); err != nil {
t.Fatal(err)
}
}
// Wait for expiration.
conf.Clock.Jump(time.Minute + time.Second)
time.Sleep(time.Millisecond * 5)
// Check counters.
k, n, b, c := l.stats()
if k != 0 || n != 0 || b != 0 || c != count {
t.Errorf("unexpected stats: %d, %d, %d, %d", k, n, b, c)
}
// Close cache.
if err = cache.Close(); err != nil {
t.Error(err.Error())
}
})
}