Skip to content

Commit

Permalink
Add NewMust
Browse files Browse the repository at this point in the history
  • Loading branch information
motoki317 committed Apr 17, 2022
1 parent 1bd9d0d commit acd525c
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 1 deletion.
9 changes: 9 additions & 0 deletions cache.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,15 @@ import (

type replaceFunc[K comparable, V any] func(ctx context.Context, key K) (V, error)

// NewMust is similar to New, but panics on error.
func NewMust[K comparable, V any](replaceFn replaceFunc[K, V], freshFor, ttl time.Duration, options ...CacheOption) *Cache[K, V] {
c, err := New(replaceFn, freshFor, ttl, options...)
if err != nil {
panic(err)
}
return c
}

// New creates a new cache instance.
// You can specify ttl longer than freshFor to achieve 'graceful cache replacement', where stale item is served via Get
// while a single goroutine is launched in the background to retrieve a fresh item.
Expand Down
25 changes: 24 additions & 1 deletion cache_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,30 @@ import (
"github.com/stretchr/testify/assert"
)

// TestNew tests the behavior of New.
func TestNewMust(t *testing.T) {
t.Parallel()

fn := func(ctx context.Context, s string) (string, error) { return "", nil }

t.Run("success", func(t *testing.T) {
t.Parallel()

_ = NewMust(fn, 0, 0)
})
t.Run("fail", func(t *testing.T) {
t.Parallel()

func() {
defer func() {
err := recover()
assert.NotNil(t, err)
}()

_ = NewMust(fn, -1, -1)
}()
})
}

func TestNew(t *testing.T) {
t.Parallel()

Expand Down

0 comments on commit acd525c

Please sign in to comment.