Skip to content

Commit

Permalink
Adding config validation when creating new cache. (#299)
Browse files Browse the repository at this point in the history
  • Loading branch information
panmari committed Nov 24, 2021
1 parent 16df11e commit be11930
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 12 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
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

0 comments on commit be11930

Please sign in to comment.