From d5307b40afc4228f603871e752b44ea8cde1c0c9 Mon Sep 17 00:00:00 2001 From: David Palm Date: Wed, 3 Feb 2016 16:07:59 +0100 Subject: [PATCH 1/2] Fetch does not return stale items --- cache.go | 8 ++++---- cache_test.go | 19 ++++++++++++++++++- 2 files changed, 22 insertions(+), 5 deletions(-) diff --git a/cache.go b/cache.go index 185177c..81cbfde 100644 --- a/cache.go +++ b/cache.go @@ -81,12 +81,12 @@ func (c *Cache) Replace(key string, value interface{}) bool { return true } -// Attempts to get the value from the cache and calles fetch on a miss. -// If fetch returns an error, no value is cached and the error is returned back -// to the caller. +// Attempts to get the value from the cache and calles fetch on a miss (missing +// or stale item). If fetch returns an error, no value is cached and the error +// is returned back to the caller. func (c *Cache) Fetch(key string, duration time.Duration, fetch func() (interface{}, error)) (*Item, error) { item := c.Get(key) - if item != nil { + if item != nil && !item.Expired() { return item, nil } value, err := fetch() diff --git a/cache_test.go b/cache_test.go index 3e85b8b..39136d1 100644 --- a/cache_test.go +++ b/cache_test.go @@ -1,10 +1,11 @@ package ccache import ( - . "github.com/karlseguin/expect" "strconv" "testing" "time" + + . "github.com/karlseguin/expect" ) type CacheTests struct{} @@ -22,6 +23,22 @@ func (_ CacheTests) DeletesAValue() { Expect(cache.Get("worm").Value()).To.Equal("sand") } +func (_ CacheTests) FetchesExpiredItems() { + cache := New(Configure()) + fn := func() (interface{}, error) { return "moo-moo", nil } + + cache.Set("beef", "moo", time.Second) + Expect(cache.Get("beef").Value()).To.Equal("moo") + + out, _ := cache.Fetch("beef", time.Second, fn) + Expect(out.Value()).To.Equal("moo") + + time.Sleep(2 * time.Second) + + out2, _ := cache.Fetch("beef", time.Second, fn) + Expect(out2.Value()).To.Equal("moo-moo") +} + func (_ CacheTests) GCsTheOldestItems() { cache := New(Configure().ItemsToPrune(10)) for i := 0; i < 500; i++ { From 3665b16e833246dd695d329ee9b23a3b0dc5bb90 Mon Sep 17 00:00:00 2001 From: David Palm Date: Fri, 5 Feb 2016 14:34:58 +0100 Subject: [PATCH 2/2] Better test --- cache_test.go | 9 ++------- 1 file changed, 2 insertions(+), 7 deletions(-) diff --git a/cache_test.go b/cache_test.go index 39136d1..d0989fb 100644 --- a/cache_test.go +++ b/cache_test.go @@ -27,16 +27,11 @@ func (_ CacheTests) FetchesExpiredItems() { cache := New(Configure()) fn := func() (interface{}, error) { return "moo-moo", nil } - cache.Set("beef", "moo", time.Second) + cache.Set("beef", "moo", time.Second*-1) Expect(cache.Get("beef").Value()).To.Equal("moo") out, _ := cache.Fetch("beef", time.Second, fn) - Expect(out.Value()).To.Equal("moo") - - time.Sleep(2 * time.Second) - - out2, _ := cache.Fetch("beef", time.Second, fn) - Expect(out2.Value()).To.Equal("moo-moo") + Expect(out.Value()).To.Equal("moo-moo") } func (_ CacheTests) GCsTheOldestItems() {