| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
|
| 14 |
|
| 15 |
|
| 16 |
|
| 17 |
package lru |
| 18 |
|
| 19 |
import ( |
| 20 |
"fmt" |
| 21 |
"testing" |
| 22 |
) |
| 23 |
|
| 24 |
type simpleStruct struct { |
| 25 |
int |
| 26 |
string |
| 27 |
} |
| 28 |
|
| 29 |
type complexStruct struct { |
| 30 |
int |
| 31 |
simpleStruct |
| 32 |
} |
| 33 |
|
| 34 |
var getTests = []struct { |
| 35 |
name string |
| 36 |
keyToAdd interface{} |
| 37 |
keyToGet interface{} |
| 38 |
expectedOk bool |
| 39 |
}{ |
| 40 |
{"string_hit", "myKey", "myKey", true}, |
| 41 |
{"string_miss", "myKey", "nonsense", false}, |
| 42 |
{"simple_struct_hit", simpleStruct{1, "two"}, simpleStruct{1, "two"}, true}, |
| 43 |
{"simple_struct_miss", simpleStruct{1, "two"}, simpleStruct{0, "noway"}, false}, |
| 44 |
{"complex_struct_hit", complexStruct{1, simpleStruct{2, "three"}}, |
| 45 |
complexStruct{1, simpleStruct{2, "three"}}, true}, |
| 46 |
} |
| 47 |
|
| 48 |
func TestGet(t *testing.T) { |
| 49 |
for _, tt := range getTests { |
| 50 |
lru := New(0) |
| 51 |
lru.Add(tt.keyToAdd, 1234) |
| 52 |
val, ok := lru.Get(tt.keyToGet) |
| 53 |
if ok != tt.expectedOk { |
| 54 |
t.Fatalf("%s: cache hit = %v; want %v", tt.name, ok, !ok) |
| 55 |
} else if ok && val != 1234 { |
| 56 |
t.Fatalf("%s expected get to return 1234 but got %v", tt.name, val) |
| 57 |
} |
| 58 |
} |
| 59 |
} |
| 60 |
|
| 61 |
func TestRemove(t *testing.T) { |
| 62 |
lru := New(0) |
| 63 |
lru.Add("myKey", 1234) |
| 64 |
if val, ok := lru.Get("myKey"); !ok { |
| 65 |
t.Fatal("TestRemove returned no match") |
| 66 |
} else if val != 1234 { |
| 67 |
t.Fatalf("TestRemove failed. Expected %d, got %v", 1234, val) |
| 68 |
} |
| 69 |
|
| 70 |
lru.Remove("myKey") |
| 71 |
if _, ok := lru.Get("myKey"); ok { |
| 72 |
t.Fatal("TestRemove returned a removed entry") |
| 73 |
} |
| 74 |
} |
| 75 |
|
| 76 |
func TestEvict(t *testing.T) { |
| 77 |
evictedKeys := make([]Key, 0) |
| 78 |
onEvictedFun := func(key Key, value interface{}) { |
| 79 |
evictedKeys = append(evictedKeys, key) |
| 80 |
} |
| 81 |
|
| 82 |
lru := New(20) |
| 83 |
lru.OnEvicted = onEvictedFun |
| 84 |
for i := 0; i < 22; i++ { |
| 85 |
lru.Add(fmt.Sprintf("myKey%d", i), 1234) |
| 86 |
} |
| 87 |
|
| 88 |
if len(evictedKeys) != 2 { |
| 89 |
t.Fatalf("got %d evicted keys; want 2", len(evictedKeys)) |
| 90 |
} |
| 91 |
if evictedKeys[0] != Key("myKey0") { |
| 92 |
t.Fatalf("got %v in first evicted key; want %s", evictedKeys[0], "myKey0") |
| 93 |
} |
| 94 |
if evictedKeys[1] != Key("myKey1") { |
| 95 |
t.Fatalf("got %v in second evicted key; want %s", evictedKeys[1], "myKey1") |
| 96 |
} |
| 97 |
} |