| 1 | package gcache |
| 2 | |
| 3 | import ( |
| 4 | "fmt" |
| 5 | "testing" |
| 6 | "time" |
| 7 | ) |
| 8 | |
| 9 | func TestSimpleGet(t *testing.T) { |
| 10 | size := 1000 |
| 11 | gc := buildTestCache(t, TYPE_SIMPLE, size) |
| 12 | testSetCache(t, gc, size) |
| 13 | testGetCache(t, gc, size) |
| 14 | } |
| 15 | |
| 16 | func TestLoadingSimpleGet(t *testing.T) { |
| 17 | size := 1000 |
| 18 | numbers := 1000 |
| 19 | testGetCache(t, buildTestLoadingCache(t, TYPE_SIMPLE, size, loader), numbers) |
| 20 | } |
| 21 | |
| 22 | func TestSimpleLength(t *testing.T) { |
| 23 | gc := buildTestLoadingCache(t, TYPE_SIMPLE, 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 TestSimpleEvictItem(t *testing.T) { |
| 34 | cacheSize := 10 |
| 35 | numbers := 11 |
| 36 | gc := buildTestLoadingCache(t, TYPE_SIMPLE, 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 TestSimpleUnboundedNoEviction(t *testing.T) { |
| 47 | numbers := 1000 |
| 48 | size_tracker := 0 |
| 49 | gcu := buildTestLoadingCache(t, TYPE_SIMPLE, 0, loader) |
| 50 | |
| 51 | for i := 0; i < numbers; i++ { |
| 52 | current_size := gcu.Len(true) |
| 53 | if current_size != size_tracker { |
| 54 | t.Errorf("Excepted cache size is %v not %v", current_size, size_tracker) |
| 55 | } |
| 56 | |
| 57 | _, err := gcu.Get(fmt.Sprintf("Key-%d", i)) |
| 58 | if err != nil { |
| 59 | t.Errorf("Unexpected error: %v", err) |
| 60 | } |
| 61 | |
| 62 | size_tracker++ |
| 63 | } |
| 64 | } |
| 65 | |
| 66 | func TestSimpleGetIFPresent(t *testing.T) { |
| 67 | testGetIFPresent(t, TYPE_SIMPLE) |
| 68 | } |
| 69 | |
| 70 | func TestSimpleHas(t *testing.T) { |
| 71 | gc := buildTestLoadingCacheWithExpiration(t, TYPE_SIMPLE, 2, 10*time.Millisecond) |
| 72 | |
| 73 | for i := 0; i < 10; i++ { |
| 74 | t.Run(fmt.Sprint(i), func(t *testing.T) { |
| 75 | gc.Get("test1") |
| 76 | gc.Get("test2") |
| 77 | |
| 78 | if gc.Has("test0") { |
| 79 | t.Fatal("should not have test0") |
| 80 | } |
| 81 | if !gc.Has("test1") { |
| 82 | t.Fatal("should have test1") |
| 83 | } |
| 84 | if !gc.Has("test2") { |
| 85 | t.Fatal("should have test2") |
| 86 | } |
| 87 | |
| 88 | time.Sleep(20 * time.Millisecond) |
| 89 | |
| 90 | if gc.Has("test0") { |
| 91 | t.Fatal("should not have test0") |
| 92 | } |
| 93 | if gc.Has("test1") { |
| 94 | t.Fatal("should not have test1") |
| 95 | } |
| 96 | if gc.Has("test2") { |
| 97 | t.Fatal("should not have test2") |
| 98 | } |
| 99 | }) |
| 100 | } |
| 101 | } |