Skip to content

Commit

Permalink
Merge pull request #9 from wI2L/cache-length
Browse files Browse the repository at this point in the history
cache: add Len() method to Cache type.
  • Loading branch information
Alkorin authored Nov 6, 2017
2 parents 4698017 + eb2b385 commit da50929
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 0 deletions.
8 changes: 8 additions & 0 deletions cache.go
Original file line number Diff line number Diff line change
Expand Up @@ -212,3 +212,11 @@ func (c *Cache) Set(key string, i interface{}) {
c.cache[key] = &CachedElement{Value: i, Timestamp: time.Now()}
c.cacheMutex.Unlock()
}

// Len returns the length of the cache.
func (c *Cache) Len() int {
c.cacheMutex.RLock()
defer c.cacheMutex.RUnlock()

return len(c.cache)
}
14 changes: 14 additions & 0 deletions cache_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,10 @@ func Test(t *testing.T) {
if nbHit != 2 { // foo1, bar1
t.Errorf("Should have 2 hits on cache getter func after foo1/bar1, got %d", nbHit)
}
cacheLen := cache.Len()
if cacheLen != 2 {
t.Errorf("expected cache length to be 2, got %d", cacheLen)
}

time.Sleep(1 * time.Second) // Sleep to force expiration
// Concurrent get (cache queue)
Expand Down Expand Up @@ -71,7 +75,12 @@ func Test(t *testing.T) {
if nbHit != 4 { // foo1, bar1, foo3, foo5
t.Errorf("Should have 4 hits on cache getter func after foo5, got %d", nbHit)
}
time.Sleep(1 * time.Second)

cacheLen = cache.Len()
if cacheLen != 0 {
t.Errorf("expected cache length to be 0, got %d", cacheLen)
}
}

func TestError(t *testing.T) {
Expand Down Expand Up @@ -151,4 +160,9 @@ func TestSet(t *testing.T) {
if c2 != forceSet {
t.Errorf("Expected '%s', got '%s'", forceSet, c2)
}

cacheLen := cache.Len()
if cacheLen != 1 {
t.Errorf("expected cache length to be 1, got %d", cacheLen)
}
}

0 comments on commit da50929

Please sign in to comment.