Skip to content

Commit

Permalink
Add more test cases to consistenthash and lru packages
Browse files Browse the repository at this point in the history
In consistenthash package:
Add test case for Getting from empty Hash (before any keys are added);
should return an empty string.

In lru package:
Test adding to an LRU with a MaxEntries value set. The Length of the cache
should remain constant.
Also add tests to add/get from a cleared empty cache.
  • Loading branch information
cnu committed May 8, 2017
1 parent b710c84 commit 0dc10b2
Show file tree
Hide file tree
Showing 2 changed files with 59 additions and 0 deletions.
6 changes: 6 additions & 0 deletions consistenthash/consistenthash_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,12 @@ func TestHashing(t *testing.T) {
return uint32(i)
})

// Get a value before any key is added to the hash
// Should yield an empty string
if emptyHashValue := hash.Get("empty hash key"); emptyHashValue != "" {
t.Errorf("Get on an empty hash = %q; want empty string", emptyHashValue)
}

// Given the above hash function, this will give replicas with "hashes":
// 2, 4, 6, 12, 14, 16, 22, 24, 26
hash.Add("6", "4", "2")
Expand Down
53 changes: 53 additions & 0 deletions lru/lru_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -71,3 +71,56 @@ func TestRemove(t *testing.T) {
t.Fatal("TestRemove returned a removed entry")
}
}

func TestAddWithMaxEntries(t *testing.T) {
lru := New(3)
items := []struct {
key string
value string
shouldExist bool
}{
{"one", "1", false},
{"two", "2", true},
{"three", "3", true},
{"four", "4", true},
{"four", "4", true},
}
for _, tt := range items {
lru.Add(tt.key, tt.value)
}
if lru.Len() != 3 {
t.Fatalf("lru size: %d items; expected: 3 items", lru.Len())
}
for _, tt := range items {
if _, ok := lru.Get(tt.key); ok != tt.shouldExist {
t.Fatalf("value exists: %v for key:%s; expected: %v", ok, tt.key, tt.shouldExist)
}
}
}

func TestClearedCache(t *testing.T) {
lru := New(0)

// Test clearing out the cache
if lru.Clear(); lru.cache != nil && lru.ll != nil {
t.Fatalf("lru cache not Cleared")
}

// Test adding to a cache which is cleared
if lru.Add("foo", "bar"); lru.Len() != 1 {
t.Fatalf("lru size: %d items; expected: 1 item", lru.Len())
}

// Clear the cache
lru.Clear()

// Test Get from a cleared cache
if val, ok := lru.Get("foo"); val != nil || ok {
t.Fatalf("Get from cleared cache: %v, %v; expected: <nil>, false", val, ok)
}

// Test the length of a cleared cache
if length := lru.Len(); length != 0 {
t.Fatalf("Len of cleared cache: %d; expected: 0", length)
}
}

0 comments on commit 0dc10b2

Please sign in to comment.