...
1
16
17 package cache
18
19 import (
20 "fmt"
21 "testing"
22 "time"
23
24 expirationcache "k8s.io/client-go/tools/cache"
25 "k8s.io/utils/clock"
26 testingclock "k8s.io/utils/clock/testing"
27 )
28
29 type testObject struct {
30 key string
31 val string
32 }
33
34
35 func NewFakeObjectCache(f func() (interface{}, error), ttl time.Duration, clock clock.Clock) *ObjectCache {
36 ttlPolicy := &expirationcache.TTLPolicy{TTL: ttl, Clock: clock}
37 deleteChan := make(chan string, 1)
38 return &ObjectCache{
39 updater: f,
40 cache: expirationcache.NewFakeExpirationStore(stringKeyFunc, deleteChan, ttlPolicy, clock),
41 }
42 }
43
44 func TestAddAndGet(t *testing.T) {
45 testObj := testObject{
46 key: "foo",
47 val: "bar",
48 }
49 objectCache := NewFakeObjectCache(func() (interface{}, error) {
50 return nil, fmt.Errorf("Unexpected Error: updater should never be called in this test")
51 }, 1*time.Hour, testingclock.NewFakeClock(time.Now()))
52
53 err := objectCache.Add(testObj.key, testObj.val)
54 if err != nil {
55 t.Errorf("Unable to add obj %#v by key: %s", testObj, testObj.key)
56 }
57 value, err := objectCache.Get(testObj.key)
58 if err != nil {
59 t.Errorf("Unable to get obj %#v by key: %s", testObj, testObj.key)
60 }
61 if value.(string) != testObj.val {
62 t.Errorf("Expected to get cached value: %#v, but got: %s", testObj.val, value.(string))
63 }
64
65 }
66
67 func TestExpirationBasic(t *testing.T) {
68 unexpectedVal := "bar"
69 expectedVal := "bar2"
70
71 testObj := testObject{
72 key: "foo",
73 val: unexpectedVal,
74 }
75
76 fakeClock := testingclock.NewFakeClock(time.Now())
77
78 objectCache := NewFakeObjectCache(func() (interface{}, error) {
79 return expectedVal, nil
80 }, 1*time.Second, fakeClock)
81
82 err := objectCache.Add(testObj.key, testObj.val)
83 if err != nil {
84 t.Errorf("Unable to add obj %#v by key: %s", testObj, testObj.key)
85 }
86
87
88 fakeClock.Sleep(2 * time.Second)
89
90 value, err := objectCache.Get(testObj.key)
91 if err != nil {
92 t.Errorf("Unable to get obj %#v by key: %s", testObj, testObj.key)
93 }
94 if value.(string) != expectedVal {
95 t.Errorf("Expected to get cached value: %#v, but got: %s", expectedVal, value.(string))
96 }
97 }
98
View as plain text