Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Adding config validation when creating new cache. #299

Merged
merged 1 commit into from
Nov 24, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 9 additions & 1 deletion bigcache.go
Original file line number Diff line number Diff line change
Expand Up @@ -46,10 +46,18 @@ func NewBigCache(config Config) (*BigCache, error) {
}

func newBigCache(config Config, clock clock) (*BigCache, error) {

if !isPowerOfTwo(config.Shards) {
return nil, fmt.Errorf("Shards number must be power of two")
}
if config.MaxEntrySize < 0 {
return nil, fmt.Errorf("MaxEntrySize must be >= 0")
}
if config.MaxEntriesInWindow < 0 {
return nil, fmt.Errorf("MaxEntriesInWindow must be >= 0")
}
if config.HardMaxCacheSize < 0 {
return nil, fmt.Errorf("HardMaxCacheSize must be >= 0")
}

if config.Hasher == nil {
config.Hasher = newDefaultHasher()
Expand Down
40 changes: 29 additions & 11 deletions bigcache_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -156,19 +156,37 @@ func TestConstructCacheWithDefaultHasher(t *testing.T) {
assertEqual(t, true, ok)
}

func TestWillReturnErrorOnInvalidNumberOfPartitions(t *testing.T) {
func TestNewBigcacheValidation(t *testing.T) {
t.Parallel()

// given
cache, error := NewBigCache(Config{
Shards: 18,
LifeWindow: 5 * time.Second,
MaxEntriesInWindow: 10,
MaxEntrySize: 256,
})

assertEqual(t, (*BigCache)(nil), cache)
assertEqual(t, "Shards number must be power of two", error.Error())
for _, tc := range []struct {
cfg Config
want string
}{
{
cfg: Config{Shards: 18},
want: "Shards number must be power of two",
},
{
cfg: Config{Shards: 16, MaxEntriesInWindow: -1},
want: "MaxEntriesInWindow must be >= 0",
},
{
cfg: Config{Shards: 16, MaxEntrySize: -1},
want: "MaxEntrySize must be >= 0",
},
{
cfg: Config{Shards: 16, HardMaxCacheSize: -1},
want: "HardMaxCacheSize must be >= 0",
},
} {
t.Run(tc.want, func(t *testing.T) {
cache, error := NewBigCache(tc.cfg)

assertEqual(t, (*BigCache)(nil), cache)
assertEqual(t, tc.want, error.Error())
})
}
}

func TestEntryNotFound(t *testing.T) {
Expand Down