Skip to content

Commit

Permalink
Add tests for issue #31
Browse files Browse the repository at this point in the history
  • Loading branch information
René Kroon authored and ReneKroon committed Jul 28, 2020
1 parent 321b446 commit 7b73ce6
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 1 deletion.
2 changes: 1 addition & 1 deletion cache.go
Original file line number Diff line number Diff line change
Expand Up @@ -249,7 +249,7 @@ func (cache *Cache) Get(key string) (interface{}, error) {
if cache.loaderFunction != nil {
var ttl time.Duration
dataToReturn, ttl, err = cache.loaderFunction(key)
if err != nil {
if err == nil {
err = cache.SetWithTTL(key, dataToReturn, ttl)
if err != nil {
dataToReturn = nil
Expand Down
44 changes: 44 additions & 0 deletions cache_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,49 @@ func TestMain(m *testing.M) {
goleak.VerifyTestMain(m)
}

// Issue #31: loader function
func TestCache_TestLoaderFunction(t *testing.T) {
cache := NewCache()

cache.SetLoaderFunction(func(key string) (data interface{}, ttl time.Duration, err error) {
return nil, 0, ErrNotFound
})

_, err := cache.Get("1")
assert.Equal(t, ErrNotFound, err)

cache.SetLoaderFunction(func(key string) (data interface{}, ttl time.Duration, err error) {
return "1", 0, nil
})

value, found := cache.Get("1")
assert.Equal(t, nil, found)
assert.Equal(t, "1", value)

cache.Close()

value, found = cache.Get("1")
assert.Equal(t, ErrClosed, found)
assert.Equal(t, nil, value)
}

// Issue #31: edge case where cache is closed when loader function has completed
func TestCache_TestLoaderFunctionDuringClose(t *testing.T) {
cache := NewCache()

cache.SetLoaderFunction(func(key string) (data interface{}, ttl time.Duration, err error) {
cache.Close()
return "1", 0, nil
})

value, found := cache.Get("1")
assert.Equal(t, ErrClosed, found)
assert.Equal(t, nil, value)

cache.Close()

}

// Issue #28: call expirationCallback automatically on cache.Close()
func TestCache_ExpirationOnClose(t *testing.T) {

Expand Down Expand Up @@ -78,6 +121,7 @@ func TestCache_ModifyAfterClose(t *testing.T) {
assert.Equal(t, ErrClosed, cache.Purge())
assert.Equal(t, ErrClosed, cache.SetWithTTL("broken", 2, time.Minute))
assert.Equal(t, ErrClosed, cache.SetTTL(time.Hour))
assert.Equal(t, 0, cache.Count())

}

Expand Down

0 comments on commit 7b73ce6

Please sign in to comment.