coocood/freecache

Incorrect ExpiredCount in cache

freedomljc opened this issue · 1 comments

From

freecache/cache.go

Lines 163 to 164 in c5bd9d4

// ExpiredCount is a metric indicating the number of times an expire occurred.
func (cache *Cache) ExpiredCount() (count int64) {
, ExpiredCount is expected to increase once the expire happens. However, during the test, found the expiredCount doesn't get changed even if the expire happens.

Test code:

func TestLocalCacheExpiry(t *testing.T) {
	localCache := freecache.NewCache(10000)
	cacheKey := "testKey"
	// set cacheKey to expire after 1 second
	localCache.Set([]byte(cacheKey), []byte(""), 1)
	time.Sleep(100 * time.Millisecond)
	ttl, _ := localCache.TTL([]byte(cacheKey))
	assert.NotEqual(t, 0, int(ttl))
	expiredCount := localCache.ExpiredCount()
	assert.Equal(t, 0, int(expiredCount))
	_, err := localCache.Get([]byte(cacheKey))
	assert.Equal(t, nil, err)

	time.Sleep(1000 * time.Millisecond)

	ttl2, _ := localCache.TTL([]byte(cacheKey))
	// Since the time has passed over 1 second, the tt2 is expected to 0.
	assert.Equal(t, 0, int(ttl2))

	_, err2 := localCache.Get([]byte(cacheKey))
	// If not found, the error is expected.
	assert.NotEqual(t, nil, err2)

	expiredCount2 := localCache.ExpiredCount()
	// Since the cachekey become expired, and also it cannot be found in localCache, the expiredCount2 is expected to be 1.
	// However, the expiredCount2 is 0.
	assert.Equal(t,0, int(expiredCount2))
}

Not sure what happened: just changed the cacheKey, the issue goes away. Closing the ticket for now, will reopen it if I can consistently repro the issue.