Skip to content

Commit

Permalink
Adding config validation when creating new cache.
Browse files Browse the repository at this point in the history
  • Loading branch information
panmari committed Nov 23, 2021
1 parent 16df11e commit 2023806
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 9 deletions.
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
45 changes: 37 additions & 8 deletions bigcache_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -156,21 +156,50 @@ func TestConstructCacheWithDefaultHasher(t *testing.T) {
assertEqual(t, true, ok)
}

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

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

assertEqual(t, (*BigCache)(nil), cache)
assertEqual(t, "Shards number must be power of two", error.Error())
}

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

cfg := DefaultConfig(5 * time.Second)
cfg.MaxEntriesInWindow = -1
cache, error := NewBigCache(cfg)

assertEqual(t, (*BigCache)(nil), cache)
assertEqual(t, "MaxEntriesInWindow must be >= 0", error.Error())
}

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

cfg := DefaultConfig(5 * time.Second)
cfg.MaxEntrySize = -1
cache, error := NewBigCache(cfg)

assertEqual(t, (*BigCache)(nil), cache)
assertEqual(t, "MaxEntrySize must be >= 0", error.Error())
}

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

cfg := DefaultConfig(5 * time.Second)
cfg.HardMaxCacheSize = -1
cache, error := NewBigCache(cfg)

assertEqual(t, (*BigCache)(nil), cache)
assertEqual(t, "HardMaxCacheSize must be >= 0", error.Error())
}

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

Expand Down

0 comments on commit 2023806

Please sign in to comment.