| 1 | package gcache |
| 2 | |
| 3 | import ( |
| 4 | "fmt" |
| 5 | "testing" |
| 6 | "time" |
| 7 | ) |
| 8 | |
| 9 | func TestLRUGet(t *testing.T) { |
| 10 | size := 1000 |
| 11 | gc := buildTestCache(t, TYPE_LRU, size) |
| 12 | testSetCache(t, gc, size) |
| 13 | testGetCache(t, gc, size) |
| 14 | } |
| 15 | |
| 16 | func TestLoadingLRUGet(t *testing.T) { |
| 17 | size := 1000 |
| 18 | gc := buildTestLoadingCache(t, TYPE_LRU, size, loader) |
| 19 | testGetCache(t, gc, size) |
| 20 | } |
| 21 | |
| 22 | func TestLRULength(t *testing.T) { |
| 23 | gc := buildTestLoadingCache(t, TYPE_LRU, 1000, loader) |
| 24 | gc.Get("test1") |
| 25 | gc.Get("test2") |
| 26 | length := gc.Len(true) |
| 27 | expectedLength := 2 |
| 28 | if length != expectedLength { |
| 29 | t.Errorf("Expected length is %v, not %v", length, expectedLength) |
| 30 | } |
| 31 | } |
| 32 | |
| 33 | func TestLRUEvictItem(t *testing.T) { |
| 34 | cacheSize := 10 |
| 35 | numbers := 11 |
| 36 | gc := buildTestLoadingCache(t, TYPE_LRU, cacheSize, loader) |
| 37 | |
| 38 | for i := 0; i < numbers; i++ { |
| 39 | _, err := gc.Get(fmt.Sprintf("Key-%d", i)) |
| 40 | if err != nil { |
| 41 | t.Errorf("Unexpected error: %v", err) |
| 42 | } |
| 43 | } |
| 44 | } |
| 45 | |
| 46 | func TestLRUGetIFPresent(t *testing.T) { |
| 47 | testGetIFPresent(t, TYPE_LRU) |
| 48 | } |
| 49 | |
| 50 | func TestLRUHas(t *testing.T) { |
| 51 | gc := buildTestLoadingCacheWithExpiration(t, TYPE_LRU, 2, 10*time.Millisecond) |
| 52 | |
| 53 | for i := 0; i < 10; i++ { |
| 54 | t.Run(fmt.Sprint(i), func(t *testing.T) { |
| 55 | gc.Get("test1") |
| 56 | gc.Get("test2") |
| 57 | |
| 58 | if gc.Has("test0") { |
| 59 | t.Fatal("should not have test0") |
| 60 | } |
| 61 | if !gc.Has("test1") { |
| 62 | t.Fatal("should have test1") |
| 63 | } |
| 64 | if !gc.Has("test2") { |
| 65 | t.Fatal("should have test2") |
| 66 | } |
| 67 | |
| 68 | time.Sleep(20 * time.Millisecond) |
| 69 | |
| 70 | if gc.Has("test0") { |
| 71 | t.Fatal("should not have test0") |
| 72 | } |
| 73 | if gc.Has("test1") { |
| 74 | t.Fatal("should not have test1") |
| 75 | } |
| 76 | if gc.Has("test2") { |
| 77 | t.Fatal("should not have test2") |
| 78 | } |
| 79 | }) |
| 80 | } |
| 81 | } |