mirror of
https://github.com/mailgun/groupcache.git
synced 2024-11-16 14:10:04 +00:00
Fix LRU to correct evict cache items when replaced (#52)
This commit is contained in:
parent
2bec0534cf
commit
a139af4144
@ -535,3 +535,18 @@ func TestContextDeadlineOnPeer(t *testing.T) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestCacheRemovesBytesOfReplacedValues(t *testing.T) {
|
||||
c := cache{}
|
||||
|
||||
const key = "test"
|
||||
keyLen := len(key)
|
||||
|
||||
for _, bytes := range []int{100, 1000, 2000} {
|
||||
c.add(key, ByteView{b: make([]byte, bytes)})
|
||||
expected := int64(bytes + keyLen)
|
||||
if c.nbytes != expected {
|
||||
t.Fatalf("%s: expected %d was %d", t.Name(), expected, c.nbytes)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -63,8 +63,12 @@ func (c *Cache) Add(key Key, value interface{}, expire time.Time) {
|
||||
c.ll = list.New()
|
||||
}
|
||||
if ee, ok := c.cache[key]; ok {
|
||||
eee := ee.Value.(*entry)
|
||||
if c.OnEvicted != nil {
|
||||
c.OnEvicted(key, eee.value)
|
||||
}
|
||||
c.ll.MoveToFront(ee)
|
||||
ee.Value.(*entry).value = value
|
||||
eee.value = value
|
||||
return
|
||||
}
|
||||
ele := c.ll.PushFront(&entry{key, value, expire})
|
||||
|
@ -46,6 +46,32 @@ var getTests = []struct {
|
||||
complexStruct{1, simpleStruct{2, "three"}}, true},
|
||||
}
|
||||
|
||||
func TestAdd_evictsOldAndReplaces(t *testing.T) {
|
||||
var evictedKey Key
|
||||
var evictedValue interface{}
|
||||
lru := New(0)
|
||||
lru.OnEvicted = func(key Key, value interface{}) {
|
||||
evictedKey = key
|
||||
evictedValue = value
|
||||
}
|
||||
lru.Add("myKey", 1234, time.Time{})
|
||||
lru.Add("myKey", 1235, time.Time{})
|
||||
|
||||
newVal, ok := lru.Get("myKey")
|
||||
if !ok {
|
||||
t.Fatalf("%s: cache hit = %v; want %v", t.Name(), ok, !ok)
|
||||
}
|
||||
if newVal != 1235 {
|
||||
t.Fatalf("%s: cache hit = %v; want %v", t.Name(), newVal, 1235)
|
||||
}
|
||||
if evictedKey != "myKey" {
|
||||
t.Fatalf("%s: evictedKey = %v; want %v", t.Name(), evictedKey, "myKey")
|
||||
}
|
||||
if evictedValue != 1234 {
|
||||
t.Fatalf("%s: evictedValue = %v; want %v", t.Name(), evictedValue, 1234)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGet(t *testing.T) {
|
||||
for _, tt := range getTests {
|
||||
lru := New(0)
|
||||
|
Loading…
Reference in New Issue
Block a user