Skip to content

Commit 0dc10b2

Browse files
committed
Add more test cases to consistenthash and lru packages
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.
1 parent b710c84 commit 0dc10b2

File tree

2 files changed

+59
-0
lines changed

2 files changed

+59
-0
lines changed

consistenthash/consistenthash_test.go

+6
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,12 @@ func TestHashing(t *testing.T) {
3434
return uint32(i)
3535
})
3636

37+
// Get a value before any key is added to the hash
38+
// Should yield an empty string
39+
if emptyHashValue := hash.Get("empty hash key"); emptyHashValue != "" {
40+
t.Errorf("Get on an empty hash = %q; want empty string", emptyHashValue)
41+
}
42+
3743
// Given the above hash function, this will give replicas with "hashes":
3844
// 2, 4, 6, 12, 14, 16, 22, 24, 26
3945
hash.Add("6", "4", "2")

lru/lru_test.go

+53
Original file line numberDiff line numberDiff line change
@@ -71,3 +71,56 @@ func TestRemove(t *testing.T) {
7171
t.Fatal("TestRemove returned a removed entry")
7272
}
7373
}
74+
75+
func TestAddWithMaxEntries(t *testing.T) {
76+
lru := New(3)
77+
items := []struct {
78+
key string
79+
value string
80+
shouldExist bool
81+
}{
82+
{"one", "1", false},
83+
{"two", "2", true},
84+
{"three", "3", true},
85+
{"four", "4", true},
86+
{"four", "4", true},
87+
}
88+
for _, tt := range items {
89+
lru.Add(tt.key, tt.value)
90+
}
91+
if lru.Len() != 3 {
92+
t.Fatalf("lru size: %d items; expected: 3 items", lru.Len())
93+
}
94+
for _, tt := range items {
95+
if _, ok := lru.Get(tt.key); ok != tt.shouldExist {
96+
t.Fatalf("value exists: %v for key:%s; expected: %v", ok, tt.key, tt.shouldExist)
97+
}
98+
}
99+
}
100+
101+
func TestClearedCache(t *testing.T) {
102+
lru := New(0)
103+
104+
// Test clearing out the cache
105+
if lru.Clear(); lru.cache != nil && lru.ll != nil {
106+
t.Fatalf("lru cache not Cleared")
107+
}
108+
109+
// Test adding to a cache which is cleared
110+
if lru.Add("foo", "bar"); lru.Len() != 1 {
111+
t.Fatalf("lru size: %d items; expected: 1 item", lru.Len())
112+
}
113+
114+
// Clear the cache
115+
lru.Clear()
116+
117+
// Test Get from a cleared cache
118+
if val, ok := lru.Get("foo"); val != nil || ok {
119+
t.Fatalf("Get from cleared cache: %v, %v; expected: <nil>, false", val, ok)
120+
}
121+
122+
// Test the length of a cleared cache
123+
if length := lru.Len(); length != 0 {
124+
t.Fatalf("Len of cleared cache: %d; expected: 0", length)
125+
}
126+
}

0 commit comments

Comments
 (0)