| 1 | package gocache |
| 2 | |
| 3 | import ( |
| 4 | "bytes" |
| 5 | "fmt" |
| 6 | "math/rand" |
| 7 | "strconv" |
| 8 | "strings" |
| 9 | "testing" |
| 10 | "time" |
| 11 | ) |
| 12 | |
| 13 | func TestNewCache(t *testing.T) { |
| 14 | cache := NewCache().WithMaxSize(1234).WithEvictionPolicy(LeastRecentlyUsed) |
| 15 | if cache.MaxMemoryUsage() != NoMaxMemoryUsage { |
| 16 | t.Error("shouldn't have a max memory usage configured") |
| 17 | } |
| 18 | if cache.EvictionPolicy() != LeastRecentlyUsed { |
| 19 | t.Error("should've had a LeastRecentlyUsed eviction policy") |
| 20 | } |
| 21 | if cache.defaultTTL != NoExpiration { |
| 22 | t.Error("should've had a default TTL of NoExpiration") |
| 23 | } |
| 24 | if cache.MaxSize() != 1234 { |
| 25 | t.Error("should've had a max cache size of 1234") |
| 26 | } |
| 27 | if cache.MemoryUsage() != 0 { |
| 28 | t.Error("should've had a memory usage of 0") |
| 29 | } |
| 30 | } |
| 31 | |
| 32 | func TestCache_Stats(t *testing.T) { |
| 33 | cache := NewCache().WithMaxSize(1234).WithEvictionPolicy(LeastRecentlyUsed) |
| 34 | cache.Set("key", "value") |
| 35 | if cache.Stats().Hits != 0 { |
| 36 | t.Error("should have 0 hits") |
| 37 | } |
| 38 | if cache.Stats().Misses != 0 { |
| 39 | t.Error("should have 0 misses") |
| 40 | } |
| 41 | cache.Get("key") |
| 42 | if cache.Stats().Hits != 1 { |
| 43 | t.Error("should have 1 hit") |
| 44 | } |
| 45 | if cache.Stats().Misses != 0 { |
| 46 | t.Error("should have 0 misses") |
| 47 | } |
| 48 | cache.Get("key-that-does-not-exist") |
| 49 | if cache.Stats().Hits != 1 { |
| 50 | t.Error("should have 1 hit") |
| 51 | } |
| 52 | if cache.Stats().Misses != 1 { |
| 53 | t.Error("should have 1 miss") |
| 54 | } |
| 55 | } |
| 56 | |
| 57 | func TestCache_Get(t *testing.T) { |
| 58 | cache := NewCache().WithMaxSize(10) |
| 59 | cache.Set("key", "value") |
| 60 | value, ok := cache.Get("key") |
| 61 | if !ok { |
| 62 | t.Error("expected key to exist") |
| 63 | } |
| 64 | if value != "value" { |
| 65 | t.Errorf("expected: %s, but got: %s", "value", value) |
| 66 | } |
| 67 | } |
| 68 | |
| 69 | func TestCache_GetExpired(t *testing.T) { |
| 70 | cache := NewCache() |
| 71 | cache.SetWithTTL("key", "value", time.Millisecond) |
| 72 | time.Sleep(2 * time.Millisecond) |
| 73 | _, ok := cache.Get("key") |
| 74 | if ok { |
| 75 | t.Error("expected key to be expired") |
| 76 | } |
| 77 | } |
| 78 | |
| 79 | func TestCache_GetEntryThatHasNotExpiredYet(t *testing.T) { |
| 80 | cache := NewCache() |
| 81 | cache.SetWithTTL("key", "value", time.Hour) |
| 82 | _, ok := cache.Get("key") |
| 83 | if !ok { |
| 84 | t.Error("expected key to not have expired") |
| 85 | } |
| 86 | } |
| 87 | |
| 88 | func TestCache_GetValue(t *testing.T) { |
| 89 | cache := NewCache().WithMaxSize(10) |
| 90 | cache.Set("key", "value") |
| 91 | value := cache.GetValue("key") |
| 92 | if value != "value" { |
| 93 | t.Errorf("expected: %s, but got: %s", "value", value) |
| 94 | } |
| 95 | } |
| 96 | |
| 97 | func TestCache_GetByKeys(t *testing.T) { |
| 98 | cache := NewCache().WithMaxSize(10) |
| 99 | cache.Set("key1", "value1") |
| 100 | cache.Set("key2", "value2") |
| 101 | keyValues := cache.GetByKeys([]string{"key1", "key2", "key3"}) |
| 102 | if len(keyValues) != 3 { |
| 103 | t.Error("expected length of map to be 3") |
| 104 | } |
| 105 | if keyValues["key1"] != "value1" { |
| 106 | t.Errorf("expected: %s, but got: %s", "value1", keyValues["key1"]) |
| 107 | } |
| 108 | if keyValues["key2"] != "value2" { |
| 109 | t.Errorf("expected: %s, but got: %s", "value2", keyValues["key2"]) |
| 110 | } |
| 111 | if value, ok := keyValues["key3"]; !ok || value != nil { |
| 112 | t.Errorf("expected key3 to exist and be nil, but got: %s", value) |
| 113 | } |
| 114 | } |
| 115 | |
| 116 | func TestCache_GetAll(t *testing.T) { |
| 117 | cache := NewCache().WithMaxSize(10) |
| 118 | cache.Set("key1", "value1") |
| 119 | cache.Set("key2", "value2") |
| 120 | keyValues := cache.GetAll() |
| 121 | if len(keyValues) != 2 { |
| 122 | t.Error("expected length of map to be 2") |
| 123 | } |
| 124 | if keyValues["key1"] != "value1" { |
| 125 | t.Errorf("expected: %s, but got: %s", "value1", keyValues["key1"]) |
| 126 | } |
| 127 | if keyValues["key2"] != "value2" { |
| 128 | t.Errorf("expected: %s, but got: %s", "value2", keyValues["key2"]) |
| 129 | } |
| 130 | } |
| 131 | |
| 132 | func TestCache_GetAllWhenOneKeyIsExpired(t *testing.T) { |
| 133 | cache := NewCache().WithMaxSize(10) |
| 134 | cache.Set("key1", "value1") |
| 135 | cache.Set("key2", "value2") |
| 136 | cache.SetWithTTL("key3", "value3", time.Nanosecond) |
| 137 | time.Sleep(time.Millisecond) |
| 138 | keyValues := cache.GetAll() |
| 139 | if len(keyValues) != 2 { |
| 140 | t.Error("expected length of map to be 2") |
| 141 | } |
| 142 | if keyValues["key1"] != "value1" { |
| 143 | t.Errorf("expected: %s, but got: %s", "value1", keyValues["key1"]) |
| 144 | } |
| 145 | if keyValues["key2"] != "value2" { |
| 146 | t.Errorf("expected: %s, but got: %s", "value2", keyValues["key2"]) |
| 147 | } |
| 148 | } |
| 149 | |
| 150 | func TestCache_GetKeysByPattern(t *testing.T) { |
| 151 | // All keys match |
| 152 | testGetKeysByPattern(t, []string{"key1", "key2", "key3", "key4"}, "key*", 0, 4) |
| 153 | testGetKeysByPattern(t, []string{"key1", "key2", "key3", "key4"}, "*y*", 0, 4) |
| 154 | testGetKeysByPattern(t, []string{"key1", "key2", "key3", "key4"}, "*key*", 0, 4) |
| 155 | testGetKeysByPattern(t, []string{"key1", "key2", "key3", "key4"}, "*", 0, 4) |
| 156 | // All keys match but limit is reached |
| 157 | testGetKeysByPattern(t, []string{"key1", "key2", "key3", "key4"}, "*", 2, 2) |
| 158 | // Some keys match |
| 159 | testGetKeysByPattern(t, []string{"key1", "key2", "key3", "key4", "key11"}, "key1*", 0, 2) |
| 160 | testGetKeysByPattern(t, []string{"key1", "key2", "key3", "key4", "key11"}, "*key1*", 0, 2) |
| 161 | testGetKeysByPattern(t, []string{"key1", "key2", "key3", "key4", "key11", "key111"}, "key1*", 0, 3) |
| 162 | testGetKeysByPattern(t, []string{"key1", "key2", "key3", "key4", "key11", "key111"}, "key11*", 0, 2) |
| 163 | testGetKeysByPattern(t, []string{"key1", "key2", "key3", "key4", "key11", "key111"}, "*11*", 0, 2) |
| 164 | testGetKeysByPattern(t, []string{"key1", "key2", "key3", "key4", "key11", "key111"}, "k*1*", 0, 3) |
| 165 | testGetKeysByPattern(t, []string{"key1", "key2", "key3", "key4", "key11", "key111"}, "*k*1", 0, 3) |
| 166 | // No keys match |
| 167 | testGetKeysByPattern(t, []string{"key1", "key2", "key3", "key4"}, "image*", 0, 0) |
| 168 | testGetKeysByPattern(t, []string{"key1", "key2", "key3", "key4"}, "?", 0, 0) |
| 169 | } |
| 170 | |
| 171 | func testGetKeysByPattern(t *testing.T, keys []string, pattern string, limit, expectedMatchingKeys int) { |
| 172 | cache := NewCache().WithMaxSize(len(keys)) |
| 173 | for _, key := range keys { |
| 174 | cache.Set(key, key) |
| 175 | } |
| 176 | matchingKeys := cache.GetKeysByPattern(pattern, limit) |
| 177 | if len(matchingKeys) != expectedMatchingKeys { |
| 178 | t.Errorf("expected to have %d keys to match pattern '%s', got %d", expectedMatchingKeys, pattern, len(matchingKeys)) |
| 179 | } |
| 180 | } |
| 181 | |
| 182 | func TestCache_GetKeysByPatternWithExpiredKey(t *testing.T) { |
| 183 | cache := NewCache().WithMaxSize(10) |
| 184 | cache.SetWithTTL("key", "value", 10*time.Millisecond) |
| 185 | // The cache entry shouldn't have expired yet, so GetKeysByPattern should return 1 key |
| 186 | if matchingKeys := cache.GetKeysByPattern("*", 0); len(matchingKeys) != 1 { |
| 187 | t.Errorf("expected to have %d keys to match pattern '%s', got %d", 1, "*", len(matchingKeys)) |
| 188 | } |
| 189 | time.Sleep(30 * time.Millisecond) |
| 190 | // Since the key expired, the same call should return 0 keys instead of 1 |
| 191 | if matchingKeys := cache.GetKeysByPattern("*", 0); len(matchingKeys) != 0 { |
| 192 | t.Errorf("expected to have %d keys to match pattern '%s', got %d", 0, "*", len(matchingKeys)) |
| 193 | } |
| 194 | } |
| 195 | |
| 196 | func TestCache_Set(t *testing.T) { |
| 197 | cache := NewCache().WithMaxSize(NoMaxSize) |
| 198 | cache.Set("key", "value") |
| 199 | value, ok := cache.Get("key") |
| 200 | if !ok { |
| 201 | t.Error("expected key to exist") |
| 202 | } |
| 203 | if value != "value" { |
| 204 | t.Errorf("expected: %s, but got: %s", "value", value) |
| 205 | } |
| 206 | cache.Set("key", "newvalue") |
| 207 | value, ok = cache.Get("key") |
| 208 | if !ok { |
| 209 | t.Error("expected key to exist") |
| 210 | } |
| 211 | if value != "newvalue" { |
| 212 | t.Errorf("expected: %s, but got: %s", "newvalue", value) |
| 213 | } |
| 214 | } |
| 215 | |
| 216 | func TestCache_SetDifferentTypesOfData(t *testing.T) { |
| 217 | cache := NewCache().WithMaxSize(NoMaxSize) |
| 218 | cache.Set("key", 1) |
| 219 | value, ok := cache.Get("key") |
| 220 | if !ok { |
| 221 | t.Error("expected key to exist") |
| 222 | } |
| 223 | if value != 1 { |
| 224 | t.Errorf("expected: %v, but got: %v", 1, value) |
| 225 | } |
| 226 | cache.Set("key", struct{ Test string }{Test: "test"}) |
| 227 | value, ok = cache.Get("key") |
| 228 | if !ok { |
| 229 | t.Error("expected key to exist") |
| 230 | } |
| 231 | if value.(struct{ Test string }) != struct{ Test string }{Test: "test"} { |
| 232 | t.Errorf("expected: %s, but got: %s", "newvalue", value) |
| 233 | } |
| 234 | } |
| 235 | |
| 236 | func TestCache_SetGetInt(t *testing.T) { |
| 237 | cache := NewCache().WithMaxSize(NoMaxSize) |
| 238 | cache.Set("key", 1) |
| 239 | value, ok := cache.Get("key") |
| 240 | if !ok { |
| 241 | t.Error("expected key to exist") |
| 242 | } |
| 243 | if value != 1 { |
| 244 | t.Errorf("expected: %v, but got: %v", 1, value) |
| 245 | } |
| 246 | cache.Set("key", 2.1) |
| 247 | value, ok = cache.Get("key") |
| 248 | if !ok { |
| 249 | t.Error("expected key to exist") |
| 250 | } |
| 251 | if value != 2.1 { |
| 252 | t.Errorf("expected: %v, but got: %v", 2.1, value) |
| 253 | } |
| 254 | } |
| 255 | |
| 256 | func TestCache_SetGetBool(t *testing.T) { |
| 257 | cache := NewCache().WithMaxSize(NoMaxSize) |
| 258 | cache.Set("key", true) |
| 259 | value, ok := cache.Get("key") |
| 260 | if !ok { |
| 261 | t.Error("expected key to exist") |
| 262 | } |
| 263 | if value != true { |
| 264 | t.Errorf("expected: %v, but got: %v", true, value) |
| 265 | } |
| 266 | } |
| 267 | |
| 268 | func TestCache_SetGetByteSlice(t *testing.T) { |
| 269 | cache := NewCache().WithMaxSize(NoMaxSize) |
| 270 | cache.Set("key", []byte("hey")) |
| 271 | value, ok := cache.Get("key") |
| 272 | if !ok { |
| 273 | t.Error("expected key to exist") |
| 274 | } |
| 275 | if bytes.Compare(value.([]byte), []byte("hey")) != 0 { |
| 276 | t.Errorf("expected: %v, but got: %v", []byte("hey"), value) |
| 277 | } |
| 278 | } |
| 279 | |
| 280 | func TestCache_SetGetStringSlice(t *testing.T) { |
| 281 | cache := NewCache().WithMaxSize(NoMaxSize) |
| 282 | cache.Set("key", []string{"john", "doe"}) |
| 283 | value, ok := cache.Get("key") |
| 284 | if !ok { |
| 285 | t.Error("expected key to exist") |
| 286 | } |
| 287 | if value.([]string)[0] != "john" { |
| 288 | t.Errorf("expected: %v, but got: %v", "john", value) |
| 289 | } |
| 290 | if value.([]string)[1] != "doe" { |
| 291 | t.Errorf("expected: %v, but got: %v", "doe", value) |
| 292 | } |
| 293 | } |
| 294 | |
| 295 | func TestCache_SetGetStruct(t *testing.T) { |
| 296 | cache := NewCache().WithMaxSize(NoMaxSize) |
| 297 | type Custom struct { |
| 298 | Int int |
| 299 | Uint uint |
| 300 | Float32 float32 |
| 301 | String string |
| 302 | Strings []string |
| 303 | Nested struct { |
| 304 | String string |
| 305 | } |
| 306 | } |
| 307 | cache.Set("key", Custom{ |
| 308 | Int: 111, |
| 309 | Uint: 222, |
| 310 | Float32: 123.456, |
| 311 | String: "hello", |
| 312 | Strings: []string{"s1", "s2"}, |
| 313 | Nested: struct{ String string }{String: "nested field"}, |
| 314 | }) |
| 315 | value, ok := cache.Get("key") |
| 316 | if !ok { |
| 317 | t.Error("expected key to exist") |
| 318 | } |
| 319 | if ExpectedValue := 111; value.(Custom).Int != ExpectedValue { |
| 320 | t.Errorf("expected: %v, but got: %v", ExpectedValue, value) |
| 321 | } |
| 322 | if ExpectedValue := uint(222); value.(Custom).Uint != ExpectedValue { |
| 323 | t.Errorf("expected: %v, but got: %v", ExpectedValue, value) |
| 324 | } |
| 325 | if ExpectedValue := float32(123.456); value.(Custom).Float32 != ExpectedValue { |
| 326 | t.Errorf("expected: %v, but got: %v", ExpectedValue, value) |
| 327 | } |
| 328 | if ExpectedValue := "hello"; value.(Custom).String != ExpectedValue { |
| 329 | t.Errorf("expected: %v, but got: %v", ExpectedValue, value) |
| 330 | } |
| 331 | if ExpectedValue := "s1"; value.(Custom).Strings[0] != ExpectedValue { |
| 332 | t.Errorf("expected: %v, but got: %v", ExpectedValue, value) |
| 333 | } |
| 334 | if ExpectedValue := "s2"; value.(Custom).Strings[1] != ExpectedValue { |
| 335 | t.Errorf("expected: %v, but got: %v", ExpectedValue, value) |
| 336 | } |
| 337 | if ExpectedValue := "nested field"; value.(Custom).Nested.String != ExpectedValue { |
| 338 | t.Errorf("expected: %v, but got: %v", ExpectedValue, value) |
| 339 | } |
| 340 | } |
| 341 | |
| 342 | func TestCache_SetAll(t *testing.T) { |
| 343 | cache := NewCache().WithMaxSize(NoMaxSize) |
| 344 | cache.SetAll(map[string]any{"k1": "v1", "k2": "v2"}) |
| 345 | value, ok := cache.Get("k1") |
| 346 | if !ok { |
| 347 | t.Error("expected key to exist") |
| 348 | } |
| 349 | if value != "v1" { |
| 350 | t.Errorf("expected: %s, but got: %s", "v1", value) |
| 351 | } |
| 352 | value, ok = cache.Get("k2") |
| 353 | if !ok { |
| 354 | t.Error("expected key to exist") |
| 355 | } |
| 356 | if value != "v2" { |
| 357 | t.Errorf("expected: %s, but got: %s", "v2", value) |
| 358 | } |
| 359 | cache.SetAll(map[string]any{"k1": "updated"}) |
| 360 | value, ok = cache.Get("k1") |
| 361 | if !ok { |
| 362 | t.Error("expected key to exist") |
| 363 | } |
| 364 | if value != "updated" { |
| 365 | t.Errorf("expected: %s, but got: %s", "updated", value) |
| 366 | } |
| 367 | } |
| 368 | |
| 369 | func TestCache_SetWithTTL(t *testing.T) { |
| 370 | cache := NewCache().WithMaxSize(NoMaxSize) |
| 371 | cache.SetWithTTL("key", "value", NoExpiration) |
| 372 | value, ok := cache.Get("key") |
| 373 | if !ok { |
| 374 | t.Error("expected key to exist") |
| 375 | } |
| 376 | if value != "value" { |
| 377 | t.Errorf("expected: %s, but got: %s", "value", value) |
| 378 | } |
| 379 | } |
| 380 | |
| 381 | func TestCache_SetWithTTLWhenTTLIsNegative(t *testing.T) { |
| 382 | cache := NewCache().WithMaxSize(NoMaxSize) |
| 383 | cache.SetWithTTL("key", "value", -12345) |
| 384 | _, ok := cache.Get("key") |
| 385 | if ok { |
| 386 | t.Error("expected key to not exist, because there's no point in creating a cache entry that has a negative TTL") |
| 387 | } |
| 388 | } |
| 389 | |
| 390 | func TestCache_SetWithTTLWhenTTLIsZero(t *testing.T) { |
| 391 | cache := NewCache().WithMaxSize(NoMaxSize) |
| 392 | cache.SetWithTTL("key", "value", 0) |
| 393 | _, ok := cache.Get("key") |
| 394 | if ok { |
| 395 | t.Error("expected key to not exist, because there's no point in creating a cache entry that has a TTL of 0") |
| 396 | } |
| 397 | } |
| 398 | |
| 399 | func TestCache_SetWithTTLWhenTTLIsZeroAndEntryAlreadyExists(t *testing.T) { |
| 400 | cache := NewCache().WithMaxSize(NoMaxSize) |
| 401 | cache.SetWithTTL("key", "value", NoExpiration) |
| 402 | cache.SetWithTTL("key", "value", 0) |
| 403 | _, ok := cache.Get("key") |
| 404 | if ok { |
| 405 | t.Error("expected key to not exist, because there's the entry was created with a TTL of 0, so it should have been deleted immediately") |
| 406 | } |
| 407 | } |
| 408 | |
| 409 | func TestCache_EvictionsRespectMaxSize(t *testing.T) { |
| 410 | cache := NewCache().WithMaxSize(5) |
| 411 | for n := 0; n < 10; n++ { |
| 412 | cache.Set(fmt.Sprintf("test_%d", n), []byte("value")) |
| 413 | } |
| 414 | count := cache.Count() |
| 415 | if count > 5 { |
| 416 | t.Error("Max size was set to 5, but the cache size reached a size of", count) |
| 417 | } |
| 418 | } |
| 419 | |
| 420 | func TestCache_EvictionsWithFIFO(t *testing.T) { |
| 421 | cache := NewCache().WithMaxSize(3).WithEvictionPolicy(FirstInFirstOut) |
| 422 | |
| 423 | cache.Set("1", []byte("value")) |
| 424 | cache.Set("2", []byte("value")) |
| 425 | cache.Set("3", []byte("value")) |
| 426 | _, _ = cache.Get("1") |
| 427 | cache.Set("4", []byte("value")) |
| 428 | _, ok := cache.Get("1") |
| 429 | if ok { |
| 430 | t.Error("expected key 1 to have been removed, because FIFO") |
| 431 | } |
| 432 | } |
| 433 | |
| 434 | func TestCache_EvictionsWithLRU(t *testing.T) { |
| 435 | cache := NewCache().WithMaxSize(3).WithEvictionPolicy(LeastRecentlyUsed) |
| 436 | |
| 437 | cache.Set("1", []byte("value")) |
| 438 | cache.Set("2", []byte("value")) |
| 439 | cache.Set("3", []byte("value")) |
| 440 | _, _ = cache.Get("1") |
| 441 | cache.Set("4", []byte("value")) |
| 442 | |
| 443 | _, ok := cache.Get("1") |
| 444 | if !ok { |
| 445 | t.Error("expected key 1 to still exist, because LRU") |
| 446 | } |
| 447 | } |
| 448 | |
| 449 | func TestCache_HeadToTailSimple(t *testing.T) { |
| 450 | cache := NewCache().WithMaxSize(3) |
| 451 | cache.Set("1", "1") |
| 452 | if cache.tail.Key != "1" && cache.head.Key != "1" { |
| 453 | t.Error("expected tail=1 and head=1") |
| 454 | } |
| 455 | cache.Set("2", "2") |
| 456 | if cache.tail.Key != "1" && cache.head.Key != "2" { |
| 457 | t.Error("expected tail=1 and head=2") |
| 458 | } |
| 459 | cache.Set("3", "3") |
| 460 | if cache.tail.Key != "1" && cache.head.Key != "3" { |
| 461 | t.Error("expected tail=1 and head=4") |
| 462 | } |
| 463 | cache.Set("4", "4") |
| 464 | if cache.tail.Key != "2" && cache.head.Key != "4" { |
| 465 | t.Error("expected tail=2 and head=4") |
| 466 | } |
| 467 | cache.Set("5", "5") |
| 468 | if cache.tail.Key != "3" && cache.head.Key != "5" { |
| 469 | t.Error("expected tail=3 and head=5") |
| 470 | } |
| 471 | } |
| 472 | |
| 473 | func TestCache_HeadTailWorksWithFIFO(t *testing.T) { |
| 474 | cache := NewCache().WithMaxSize(3).WithEvictionPolicy(FirstInFirstOut) |
| 475 | |
| 476 | if cache.tail != nil { |
| 477 | t.Error("cache tail should have been nil") |
| 478 | } |
| 479 | if cache.head != nil { |
| 480 | t.Error("cache head should have been nil") |
| 481 | } |
| 482 | |
| 483 | cache.Set("1", []byte("value")) |
| 484 | |
| 485 | // (head) 1 (tail) |
| 486 | if cache.tail == nil || cache.tail.Key != "1" { |
| 487 | t.Error("cache tail should have been entry with key 1") |
| 488 | } |
| 489 | if cache.head == nil || cache.head.Key != "1" { |
| 490 | t.Error("cache head should have been entry with key 1") |
| 491 | } |
| 492 | |
| 493 | cache.Set("2", []byte("value")) |
| 494 | |
| 495 | // (head) 2 - 1 (tail) |
| 496 | if cache.tail == nil || cache.tail.Key != "1" { |
| 497 | t.Error("cache tail should have been the entry with key 1") |
| 498 | } |
| 499 | if cache.head == nil || cache.head.Key != "2" { |
| 500 | t.Error("cache head should have been the entry with key 2") |
| 501 | } |
| 502 | if cache.head.next.Key != "1" { |
| 503 | t.Error("The entry key next to the cache head should have been 1") |
| 504 | } |
| 505 | if cache.head.previous != nil { |
| 506 | t.Error("The cache head should not have a previous node") |
| 507 | } |
| 508 | if cache.tail.previous.Key != "2" { |
| 509 | t.Error("The entry key previous to the cache tail should have been 2") |
| 510 | } |
| 511 | if cache.tail.next != nil { |
| 512 | t.Error("The cache tail should not have a next node") |
| 513 | } |
| 514 | |
| 515 | cache.Set("3", []byte("value")) |
| 516 | |
| 517 | // (head) 3 - 2 - 1 (tail) |
| 518 | if cache.tail == nil || cache.tail.Key != "1" { |
| 519 | t.Error("cache tail should have been the entry with key 1") |
| 520 | } |
| 521 | if cache.tail.previous.Key != "2" { |
| 522 | t.Error("The entry key previous to the cache tail should have been 2") |
| 523 | } |
| 524 | if cache.tail.next != nil { |
| 525 | t.Error("The cache tail should not have a next node") |
| 526 | } |
| 527 | if cache.head == nil || cache.head.Key != "3" { |
| 528 | t.Error("cache head should have been the entry with key 3") |
| 529 | } |
| 530 | if cache.head.next.Key != "2" { |
| 531 | t.Error("The entry key next to the cache head should have been 2") |
| 532 | } |
| 533 | if cache.head.previous != nil { |
| 534 | t.Error("The cache head should not have a previous node") |
| 535 | } |
| 536 | if cache.head.next.previous.Key != "3" { |
| 537 | t.Error("The head's next node should have its previous node pointing to the cache head") |
| 538 | } |
| 539 | if cache.head.next.next.Key != "1" { |
| 540 | t.Error("The head's next node should have its next node pointing to the cache tail") |
| 541 | } |
| 542 | |
| 543 | // Get the first entry. This doesn't change anything for FIFO, but for LRU, it would mean that retrieved entry |
| 544 | // wouldn't be evicted since it was recently accessed. Basically, we just want to make sure that FIFO works |
| 545 | // as intended (i.e. not like LRU) |
| 546 | _, _ = cache.Get("1") |
| 547 | |
| 548 | cache.Set("4", []byte("value")) |
| 549 | |
| 550 | // (head) 4 - 3 - 2 (tail) |
| 551 | _, ok := cache.Get("1") |
| 552 | if ok { |
| 553 | t.Error("expected key 1 to have been removed, because FIFO") |
| 554 | } |
| 555 | if cache.tail == nil || cache.tail.Key != "2" { |
| 556 | t.Error("cache tail should have been the entry with key 2") |
| 557 | } |
| 558 | if cache.tail.previous.Key != "3" { |
| 559 | t.Error("The entry key previous to the cache tail should have been 3") |
| 560 | } |
| 561 | if cache.tail.next != nil { |
| 562 | t.Error("The cache tail should not have a next node") |
| 563 | } |
| 564 | if cache.head == nil || cache.head.Key != "4" { |
| 565 | t.Error("cache head should have been the entry with key 4") |
| 566 | } |
| 567 | if cache.head.next.Key != "3" { |
| 568 | t.Error("The entry key next to the cache head should have been 3") |
| 569 | } |
| 570 | if cache.head.previous != nil { |
| 571 | t.Error("The cache head should not have a previous node") |
| 572 | } |
| 573 | if cache.head.next.previous.Key != "4" { |
| 574 | t.Error("The head's next node should have its previous node pointing to the cache head") |
| 575 | } |
| 576 | if cache.head.next.next.Key != "2" { |
| 577 | t.Error("The head's next node should have its next node pointing to the cache tail") |
| 578 | } |
| 579 | } |
| 580 | |
| 581 | func TestCache_HeadTailWorksWithLRU(t *testing.T) { |
| 582 | cache := NewCache().WithMaxSize(3).WithEvictionPolicy(LeastRecentlyUsed) |
| 583 | |
| 584 | if cache.tail != nil { |
| 585 | t.Error("cache tail should have been nil") |
| 586 | } |
| 587 | if cache.head != nil { |
| 588 | t.Error("cache head should have been nil") |
| 589 | } |
| 590 | |
| 591 | cache.Set("1", []byte("value")) |
| 592 | |
| 593 | // (head) 1 (tail) |
| 594 | if cache.tail == nil || cache.tail.Key != "1" { |
| 595 | t.Error("cache tail should have been entry with key 1") |
| 596 | } |
| 597 | if cache.head == nil || cache.head.Key != "1" { |
| 598 | t.Error("cache head should have been entry with key 1") |
| 599 | } |
| 600 | |
| 601 | cache.Set("2", []byte("value")) |
| 602 | |
| 603 | // (head) 2 - 1 (tail) |
| 604 | if cache.tail == nil || cache.tail.Key != "1" { |
| 605 | t.Error("cache tail should have been the entry with key 1") |
| 606 | } |
| 607 | if cache.head == nil || cache.head.Key != "2" { |
| 608 | t.Error("cache head should have been the entry with key 2") |
| 609 | } |
| 610 | if cache.head.next.Key != "1" { |
| 611 | t.Error("The entry key next to the cache head should have been 1") |
| 612 | } |
| 613 | if cache.head.previous != nil { |
| 614 | t.Error("The cache head should not have a previous node") |
| 615 | } |
| 616 | if cache.tail.previous.Key != "2" { |
| 617 | t.Error("The entry key previous to the cache tail should have been 2") |
| 618 | } |
| 619 | if cache.tail.next != nil { |
| 620 | t.Error("The cache tail should not have a next node") |
| 621 | } |
| 622 | |
| 623 | cache.Set("3", []byte("value")) |
| 624 | |
| 625 | // (head) 3 - 2 - 1 (tail) |
| 626 | if cache.tail == nil || cache.tail.Key != "1" { |
| 627 | t.Error("cache tail should have been the entry with key 1") |
| 628 | } |
| 629 | if cache.tail.previous.Key != "2" { |
| 630 | t.Error("The entry key previous to the cache tail should have been 2") |
| 631 | } |
| 632 | if cache.tail.next != nil { |
| 633 | t.Error("The cache tail should not have a next node") |
| 634 | } |
| 635 | if cache.head == nil || cache.head.Key != "3" { |
| 636 | t.Error("cache head should have been the entry with key 3") |
| 637 | } |
| 638 | if cache.head.next.Key != "2" { |
| 639 | t.Error("The entry key next to the cache head should have been 2") |
| 640 | } |
| 641 | if cache.head.previous != nil { |
| 642 | t.Error("The cache head should not have a previous node") |
| 643 | } |
| 644 | if cache.head.next.previous.Key != "3" { |
| 645 | t.Error("The head's next node should have its previous node pointing to the cache head") |
| 646 | } |
| 647 | if cache.head.next.next.Key != "1" { |
| 648 | t.Error("The head's next node should have its next node pointing to the cache tail") |
| 649 | } |
| 650 | |
| 651 | // Because we're using a LRU cache, this should cause 1 to get moved back to the head, thus |
| 652 | // moving it from the tail. |
| 653 | // In other words, because we retrieved the key 1 here, this is no longer the least recently used cache entry, |
| 654 | // which means it will not be evicted during the next insertion. |
| 655 | _, _ = cache.Get("1") |
| 656 | |
| 657 | // (head) 1 - 3 - 2 (tail) (This updated because LRU) |
| 658 | cache.Set("4", []byte("value")) |
| 659 | |
| 660 | // (head) 4 - 1 - 3 (tail) |
| 661 | if cache.tail == nil || cache.tail.Key != "3" { |
| 662 | t.Error("cache tail should have been the entry with key 3") |
| 663 | } |
| 664 | if cache.tail.previous.Key != "1" { |
| 665 | t.Error("The entry key previous to the cache tail should have been 1") |
| 666 | } |
| 667 | if cache.tail.next != nil { |
| 668 | t.Error("The cache tail should not have a next node") |
| 669 | } |
| 670 | if cache.head == nil || cache.head.Key != "4" { |
| 671 | t.Error("cache head should have been the entry with key 4") |
| 672 | } |
| 673 | if cache.head.next.Key != "1" { |
| 674 | t.Error("The entry key next to the cache head should have been 1") |
| 675 | } |
| 676 | if cache.head.previous != nil { |
| 677 | t.Error("The cache head should not have a previous node") |
| 678 | } |
| 679 | if cache.head.next.previous.Key != cache.head.Key { |
| 680 | t.Error("The head's next node should have its previous node pointing to the cache head") |
| 681 | } |
| 682 | if cache.head.next.next.Key != cache.tail.Key { |
| 683 | t.Error("Should be able to walk from head to tail") |
| 684 | } |
| 685 | if cache.tail.previous.previous != cache.head { |
| 686 | t.Error("Should be able to walk from tail to head") |
| 687 | } |
| 688 | |
| 689 | _, ok := cache.Get("1") |
| 690 | if !ok { |
| 691 | t.Error("expected key 1 to still exist, because LRU") |
| 692 | } |
| 693 | } |
| 694 | |
| 695 | func TestCache_HeadStaysTheSameIfCallRepeatedly(t *testing.T) { |
| 696 | cache := NewCache().WithEvictionPolicy(LeastRecentlyUsed).WithMaxSize(10) |
| 697 | cache.Set("1", "1") |
| 698 | if cache.tail.Key != "1" && cache.head.Key != "1" { |
| 699 | t.Error("expected tail=1 and head=1") |
| 700 | } |
| 701 | cache.Set("1", "1") |
| 702 | if cache.tail.Key != "1" && cache.head.Key != "1" { |
| 703 | t.Error("expected tail=1 and head=1") |
| 704 | } |
| 705 | cache.Get("1") |
| 706 | if cache.tail.Key != "1" && cache.head.Key != "1" { |
| 707 | t.Error("expected tail=1 and head=1") |
| 708 | } |
| 709 | cache.Get("1") |
| 710 | if cache.tail.Key != "1" && cache.head.Key != "1" { |
| 711 | t.Error("expected tail=1 and head=1") |
| 712 | } |
| 713 | } |
| 714 | |
| 715 | func TestCache_Delete(t *testing.T) { |
| 716 | cache := NewCache() |
| 717 | |
| 718 | if cache.tail != nil { |
| 719 | t.Error("cache tail should have been nil") |
| 720 | } |
| 721 | if cache.head != nil { |
| 722 | t.Error("cache head should have been nil") |
| 723 | } |
| 724 | |
| 725 | cache.Set("1", "hey") |
| 726 | cache.Set("2", []byte("sup")) |
| 727 | cache.Set("3", 123456) |
| 728 | |
| 729 | // (head) 3 - 2 - 1 (tail) |
| 730 | if cache.tail.Key != "1" { |
| 731 | t.Error("cache tail should have been the entry with key 1") |
| 732 | } |
| 733 | if cache.head.Key != "3" { |
| 734 | t.Error("cache head should have been the entry with key 3") |
| 735 | } |
| 736 | |
| 737 | cache.Delete("2") |
| 738 | |
| 739 | // (head) 3 - 1 (tail) |
| 740 | if cache.tail.Key != "1" { |
| 741 | t.Error("cache tail should have been the entry with key 1") |
| 742 | } |
| 743 | if cache.head.Key != "3" { |
| 744 | t.Error("cache head should have been the entry with key 3") |
| 745 | } |
| 746 | if cache.tail.previous.Key != "3" { |
| 747 | t.Error("The entry key previous to the cache tail should have been 3") |
| 748 | } |
| 749 | if cache.head.next.Key != "1" { |
| 750 | t.Error("The entry key next to the cache tail should have been 1") |
| 751 | } |
| 752 | |
| 753 | cache.Delete("1") |
| 754 | |
| 755 | // (head) 3 (tail) |
| 756 | if cache.tail.Key != "3" { |
| 757 | t.Error("cache tail should have been the entry with key 3") |
| 758 | } |
| 759 | if cache.head.Key != "3" { |
| 760 | t.Error("cache head should have been the entry with key 3") |
| 761 | } |
| 762 | |
| 763 | if cache.head != cache.tail { |
| 764 | t.Error("There should only be one entry in the cache") |
| 765 | } |
| 766 | if cache.head.next != nil || cache.tail.previous != nil { |
| 767 | t.Error("Since head == tail, there should be no next/prev") |
| 768 | } |
| 769 | } |
| 770 | |
| 771 | func TestCache_DeleteAll(t *testing.T) { |
| 772 | cache := NewCache() |
| 773 | cache.Set("1", []byte("1")) |
| 774 | cache.Set("2", []byte("2")) |
| 775 | cache.Set("3", []byte("3")) |
| 776 | if len(cache.GetByKeys([]string{"1", "2", "3"})) != 3 { |
| 777 | t.Error("Expected keys 1, 2 and 3 to exist") |
| 778 | } |
| 779 | numberOfDeletedKeys := cache.DeleteAll([]string{"1", "2", "3"}) |
| 780 | if numberOfDeletedKeys != 3 { |
| 781 | t.Errorf("Expected 3 keys to have been deleted, but only %d were deleted", numberOfDeletedKeys) |
| 782 | } |
| 783 | } |
| 784 | |
| 785 | func TestCache_DeleteKeysByPattern(t *testing.T) { |
| 786 | cache := NewCache() |
| 787 | cache.Set("a1", []byte("v")) |
| 788 | cache.Set("a2", []byte("v")) |
| 789 | cache.Set("b1", []byte("v")) |
| 790 | if len(cache.GetByKeys([]string{"a1", "a2", "b1"})) != 3 { |
| 791 | t.Error("Expected keys 1, 2 and 3 to exist") |
| 792 | } |
| 793 | numberOfDeletedKeys := cache.DeleteKeysByPattern("a*") |
| 794 | if numberOfDeletedKeys != 2 { |
| 795 | t.Errorf("Expected 2 keys to have been deleted, but only %d were deleted", numberOfDeletedKeys) |
| 796 | } |
| 797 | if _, exists := cache.Get("b1"); !exists { |
| 798 | t.Error("Expected key b1 to still exist") |
| 799 | } |
| 800 | } |
| 801 | |
| 802 | func TestCache_TTL(t *testing.T) { |
| 803 | cache := NewCache() |
| 804 | ttl, err := cache.TTL("key") |
| 805 | if err != ErrKeyDoesNotExist { |
| 806 | t.Errorf("expected %s, got %s", ErrKeyDoesNotExist, err) |
| 807 | } |
| 808 | cache.Set("key", "value") |
| 809 | _, err = cache.TTL("key") |
| 810 | if err != ErrKeyHasNoExpiration { |
| 811 | t.Error("Expected TTL on new key created using Set to have no expiration") |
| 812 | } |
| 813 | cache.SetWithTTL("key", "value", time.Hour) |
| 814 | ttl, err = cache.TTL("key") |
| 815 | if err != nil { |
| 816 | t.Error("Unexpected error") |
| 817 | } |
| 818 | if ttl.Minutes() < 59 || ttl.Minutes() > 60 { |
| 819 | t.Error("Expected the TTL to be almost an hour") |
| 820 | } |
| 821 | cache.SetWithTTL("key", "value", 5*time.Millisecond) |
| 822 | time.Sleep(6 * time.Millisecond) |
| 823 | ttl, err = cache.TTL("key") |
| 824 | if err != ErrKeyDoesNotExist { |
| 825 | t.Error("key should've expired, thus TTL should've returned ") |
| 826 | } |
| 827 | } |
| 828 | |
| 829 | func TestCache_Expire(t *testing.T) { |
| 830 | cache := NewCache() |
| 831 | if cache.Expire("key-that-does-not-exist", time.Minute) { |
| 832 | t.Error("Expected Expire to return false, because the key used did not exist") |
| 833 | } |
| 834 | cache.Set("key", "value") |
| 835 | _, err := cache.TTL("key") |
| 836 | if err != ErrKeyHasNoExpiration { |
| 837 | t.Error("Expected TTL on new key created using Set to have no expiration") |
| 838 | } |
| 839 | if !cache.Expire("key", time.Hour) { |
| 840 | t.Error("Expected Expire to return true") |
| 841 | } |
| 842 | ttl, err := cache.TTL("key") |
| 843 | if err != nil { |
| 844 | t.Error("Unexpected error") |
| 845 | } |
| 846 | if ttl.Minutes() < 59 || ttl.Minutes() > 60 { |
| 847 | t.Error("Expected the TTL to be almost an hour") |
| 848 | } |
| 849 | if !cache.Expire("key", 5*time.Millisecond) { |
| 850 | t.Error("Expected Expire to return true") |
| 851 | } |
| 852 | time.Sleep(6 * time.Millisecond) |
| 853 | _, err = cache.TTL("key") |
| 854 | if err != ErrKeyDoesNotExist { |
| 855 | t.Error("key should've expired, thus TTL should've returned ErrKeyDoesNotExist") |
| 856 | } |
| 857 | if cache.Expire("key", time.Hour) { |
| 858 | t.Error("Expire should've returned false, because the key should've already expired, thus no longer exist") |
| 859 | } |
| 860 | cache.SetWithTTL("key", "value", time.Hour) |
| 861 | if !cache.Expire("key", NoExpiration) { |
| 862 | t.Error("Expire should've returned true") |
| 863 | } |
| 864 | if _, err := cache.TTL("key"); err != ErrKeyHasNoExpiration { |
| 865 | t.Error("TTL should've returned ErrKeyHasNoExpiration") |
| 866 | } |
| 867 | } |
| 868 | |
| 869 | func TestCache_Clear(t *testing.T) { |
| 870 | cache := NewCache().WithMaxSize(10) |
| 871 | cache.Set("k1", "v1") |
| 872 | cache.Set("k2", "v2") |
| 873 | cache.Set("k3", "v3") |
| 874 | if cache.Count() != 3 { |
| 875 | t.Error("expected cache size to be 3, got", cache.Count()) |
| 876 | } |
| 877 | cache.Clear() |
| 878 | if cache.Count() != 0 { |
| 879 | t.Error("expected cache to be empty") |
| 880 | } |
| 881 | if cache.memoryUsage != 0 { |
| 882 | t.Error("expected cache.memoryUsage to be 0") |
| 883 | } |
| 884 | } |
| 885 | |
| 886 | func TestCache_WithMaxSize(t *testing.T) { |
| 887 | cache := NewCache().WithMaxSize(1234) |
| 888 | if cache.MaxSize() != 1234 { |
| 889 | t.Error("expected cache to have a maximum size of 1234") |
| 890 | } |
| 891 | } |
| 892 | |
| 893 | func TestCache_WithMaxSizeAndNegativeValue(t *testing.T) { |
| 894 | cache := NewCache().WithMaxSize(-10) |
| 895 | if cache.MaxSize() != NoMaxSize { |
| 896 | t.Error("expected cache to have no maximum size") |
| 897 | } |
| 898 | } |
| 899 | |
| 900 | func TestCache_WithMaxMemoryUsage(t *testing.T) { |
| 901 | const ValueSize = Kilobyte |
| 902 | cache := NewCache().WithMaxSize(0).WithMaxMemoryUsage(Kilobyte * 64) |
| 903 | for i := 0; i < 100; i++ { |
| 904 | cache.Set(fmt.Sprintf("%d", i), strings.Repeat("0", ValueSize)) |
| 905 | } |
| 906 | if cache.MemoryUsage()/1024 < 63 || cache.MemoryUsage()/1024 > 65 { |
| 907 | t.Error("expected memoryUsage to be between 63KB and 64KB") |
| 908 | } |
| 909 | } |
| 910 | |
| 911 | func TestCache_WithMaxMemoryUsageWhenAddingAnEntryThatCausesMoreThanOneEviction(t *testing.T) { |
| 912 | const ValueSize = Kilobyte |
| 913 | cache := NewCache().WithMaxSize(0).WithMaxMemoryUsage(64 * Kilobyte) |
| 914 | for i := 0; i < 100; i++ { |
| 915 | cache.Set(fmt.Sprintf("%d", i), strings.Repeat("0", ValueSize)) |
| 916 | } |
| 917 | if cache.MemoryUsage()/1024 < 63 || cache.MemoryUsage()/1024 > 65 { |
| 918 | t.Error("expected memoryUsage to be between 63KB and 64KB") |
| 919 | } |
| 920 | } |
| 921 | |
| 922 | func TestCache_WithMaxMemoryUsageAndNegativeValue(t *testing.T) { |
| 923 | cache := NewCache().WithMaxSize(0).WithMaxMemoryUsage(-1234) |
| 924 | if cache.MaxMemoryUsage() != NoMaxMemoryUsage { |
| 925 | t.Error("attempting to set a negative max memory usage should force MaxMemoryUsage to NoMaxMemoryUsage") |
| 926 | } |
| 927 | } |
| 928 | |
| 929 | func TestCache_MemoryUsageAfterSet10000AndDelete5000(t *testing.T) { |
| 930 | const ValueSize = 64 |
| 931 | cache := NewCache().WithMaxSize(10000).WithMaxMemoryUsage(Gigabyte) |
| 932 | for i := 0; i < cache.maxSize; i++ { |
| 933 | cache.Set(fmt.Sprintf("%05d", i), strings.Repeat("0", ValueSize)) |
| 934 | } |
| 935 | memoryUsageBeforeDeleting := cache.MemoryUsage() |
| 936 | for i := 0; i < cache.maxSize/2; i++ { |
| 937 | key := fmt.Sprintf("%05d", i) |
| 938 | cache.Delete(key) |
| 939 | } |
| 940 | memoryUsageRatio := float32(cache.MemoryUsage()) / float32(memoryUsageBeforeDeleting) |
| 941 | if memoryUsageRatio != 0.5 { |
| 942 | t.Error("Since half of the keys were deleted, the memoryUsage should've been half of what the memory usage was before beginning deletion") |
| 943 | } |
| 944 | } |
| 945 | |
| 946 | func TestCache_MemoryUsageIsReliable(t *testing.T) { |
| 947 | cache := NewCache().WithMaxMemoryUsage(Megabyte) |
| 948 | previousCacheMemoryUsage := cache.MemoryUsage() |
| 949 | if previousCacheMemoryUsage != 0 { |
| 950 | t.Error("cache.MemoryUsage() should've been 0") |
| 951 | } |
| 952 | cache.Set("1", 1) |
| 953 | if cache.MemoryUsage() <= previousCacheMemoryUsage { |
| 954 | t.Error("cache.MemoryUsage() should've increased") |
| 955 | } |
| 956 | previousCacheMemoryUsage = cache.MemoryUsage() |
| 957 | cache.SetAll(map[string]any{"2": "2", "3": "3", "4": "4"}) |
| 958 | if cache.MemoryUsage() <= previousCacheMemoryUsage { |
| 959 | t.Error("cache.MemoryUsage() should've increased") |
| 960 | } |
| 961 | previousCacheMemoryUsage = cache.MemoryUsage() |
| 962 | cache.Delete("2") |
| 963 | if cache.MemoryUsage() >= previousCacheMemoryUsage { |
| 964 | t.Error("cache.MemoryUsage() should've decreased") |
| 965 | } |
| 966 | previousCacheMemoryUsage = cache.MemoryUsage() |
| 967 | cache.Set("1", 1) |
| 968 | if cache.MemoryUsage() != previousCacheMemoryUsage { |
| 969 | t.Error("cache.MemoryUsage() shouldn't have changed, because the entry didn't change") |
| 970 | } |
| 971 | previousCacheMemoryUsage = cache.MemoryUsage() |
| 972 | cache.Delete("3") |
| 973 | if cache.MemoryUsage() >= previousCacheMemoryUsage { |
| 974 | t.Error("cache.MemoryUsage() should've decreased") |
| 975 | } |
| 976 | previousCacheMemoryUsage = cache.MemoryUsage() |
| 977 | cache.Delete("4") |
| 978 | if cache.MemoryUsage() >= previousCacheMemoryUsage { |
| 979 | t.Error("cache.MemoryUsage() should've decreased") |
| 980 | } |
| 981 | previousCacheMemoryUsage = cache.MemoryUsage() |
| 982 | cache.Delete("1") |
| 983 | if cache.MemoryUsage() >= previousCacheMemoryUsage || cache.memoryUsage != 0 { |
| 984 | t.Error("cache.MemoryUsage() should've been 0") |
| 985 | } |
| 986 | previousCacheMemoryUsage = cache.MemoryUsage() |
| 987 | cache.Set("1", "v4lu3") |
| 988 | if cache.MemoryUsage() <= previousCacheMemoryUsage { |
| 989 | t.Error("cache.MemoryUsage() should've increased") |
| 990 | } |
| 991 | previousCacheMemoryUsage = cache.MemoryUsage() |
| 992 | cache.Set("1", "value") |
| 993 | if cache.MemoryUsage() != previousCacheMemoryUsage { |
| 994 | t.Error("cache.MemoryUsage() shouldn't have changed") |
| 995 | } |
| 996 | previousCacheMemoryUsage = cache.MemoryUsage() |
| 997 | cache.Set("1", true) |
| 998 | if cache.MemoryUsage() >= previousCacheMemoryUsage { |
| 999 | t.Error("cache.MemoryUsage() should've decreased, because a bool uses less memory than a string") |
| 1000 | } |
| 1001 | } |
| 1002 | |
| 1003 | func TestCache_MemoryUsageAndMaxSizeIsReliable(t *testing.T) { |
| 1004 | cache := NewCache().WithMaxMemoryUsage(100 * Kilobyte).WithMaxSize(1) |
| 1005 | rand.Seed(time.Now().UnixNano()) |
| 1006 | for i := 0; i < 10000; i++ { |
| 1007 | if i%5 == 0 { |
| 1008 | cache.Set(strconv.Itoa(rand.Intn(10)), strings.Repeat("what", rand.Intn(10000))) |
| 1009 | } else { |
| 1010 | cache.Set(strconv.Itoa(rand.Intn(10)), struct { |
| 1011 | m map[string]any |
| 1012 | s string |
| 1013 | }{ |
| 1014 | m: map[string]any{ |
| 1015 | "a": "b", |
| 1016 | strings.Repeat("b", rand.Intn(1000)): map[string]string{ |
| 1017 | strings.Repeat("c", rand.Intn(1000)): "d", |
| 1018 | }, |
| 1019 | }, |
| 1020 | s: strings.Repeat("e", rand.Intn(1000)), |
| 1021 | }) |
| 1022 | } |
| 1023 | cache.Get(strconv.Itoa(rand.Intn(10))) |
| 1024 | if cache.MemoryUsage() < 0 { |
| 1025 | t.Fatal("cache.MemoryUsage() should never be negative") |
| 1026 | } |
| 1027 | } |
| 1028 | } |
| 1029 | |
| 1030 | func TestCache_WithDefaultTTL(t *testing.T) { |
| 1031 | cache := NewCache().WithDefaultTTL(5 * time.Millisecond) |
| 1032 | if cache.defaultTTL != 5*time.Millisecond { |
| 1033 | t.Error("expected defaultTTL to be 5ms") |
| 1034 | } |
| 1035 | cache.Set("1", 1) |
| 1036 | cache.SetWithTTL("2", 2, time.Hour) |
| 1037 | if cache.GetValue("1") == nil { |
| 1038 | t.Error("expected cache entry with key 1 to still exist") |
| 1039 | } |
| 1040 | if cache.GetValue("2") == nil { |
| 1041 | t.Error("expected cache entry with key 2 to still exist") |
| 1042 | } |
| 1043 | time.Sleep(10 * time.Millisecond) |
| 1044 | if cache.GetValue("1") != nil { |
| 1045 | t.Error("expected cache entry with key 1 to have expired") |
| 1046 | } |
| 1047 | if cache.GetValue("2") == nil { |
| 1048 | t.Error("expected cache entry with key 2 to still exist") |
| 1049 | } |
| 1050 | } |
| 1051 | |
| 1052 | func TestCache_WithForceNilInterfaceOnNilPointer(t *testing.T) { |
| 1053 | type Struct struct{} |
| 1054 | cache := NewCache().WithForceNilInterfaceOnNilPointer(true) |
| 1055 | cache.Set("key", (*Struct)(nil)) |
| 1056 | if value, exists := cache.Get("key"); !exists { |
| 1057 | t.Error("expected key to exist") |
| 1058 | } else { |
| 1059 | if value != nil { |
| 1060 | // the value is not nil, because cache.Get returns an interface{} (any), and the type of that interface is not nil |
| 1061 | t.Error("value should be nil") |
| 1062 | } |
| 1063 | } |
| 1064 | |
| 1065 | cache.Clear() |
| 1066 | |
| 1067 | cache = cache.WithForceNilInterfaceOnNilPointer(false) |
| 1068 | cache.Set("key", (*Struct)(nil)) |
| 1069 | if value, exists := cache.Get("key"); !exists { |
| 1070 | t.Error("expected key to exist") |
| 1071 | } else { |
| 1072 | if value == nil { |
| 1073 | t.Error("value should be not be nil, because the type of the interface is not nil") |
| 1074 | } |
| 1075 | if value.(*Struct) != nil { |
| 1076 | t.Error("casted value should be nil") |
| 1077 | } |
| 1078 | } |
| 1079 | } |
| 1080 | |
| 1081 | func TestEvictionWhenThereIsNothingToEvict(t *testing.T) { |
| 1082 | cache := NewCache() |
| 1083 | cache.evict() |
| 1084 | cache.evict() |
| 1085 | cache.evict() |
| 1086 | } |
| 1087 | |
| 1088 | func TestCache(t *testing.T) { |
| 1089 | cache := NewCache().WithMaxSize(3).WithEvictionPolicy(LeastRecentlyUsed) |
| 1090 | cache.Set("1", 1) |
| 1091 | cache.Set("2", 2) |
| 1092 | cache.Set("3", 3) |
| 1093 | cache.Set("4", 4) |
| 1094 | if _, ok := cache.Get("4"); !ok { |
| 1095 | t.Error("expected 4 to exist") |
| 1096 | } |
| 1097 | if _, ok := cache.Get("3"); !ok { |
| 1098 | t.Error("expected 3 to exist") |
| 1099 | } |
| 1100 | if _, ok := cache.Get("2"); !ok { |
| 1101 | t.Error("expected 2 to exist") |
| 1102 | } |
| 1103 | if _, ok := cache.Get("1"); ok { |
| 1104 | t.Error("expected 1 to have been evicted") |
| 1105 | } |
| 1106 | cache.Set("5", 5) |
| 1107 | if _, ok := cache.Get("1"); ok { |
| 1108 | t.Error("expected 1 to have been evicted") |
| 1109 | } |
| 1110 | if _, ok := cache.Get("2"); !ok { |
| 1111 | t.Error("expected 2 to exist") |
| 1112 | } |
| 1113 | if _, ok := cache.Get("3"); !ok { |
| 1114 | t.Error("expected 3 to exist") |
| 1115 | } |
| 1116 | if _, ok := cache.Get("4"); ok { |
| 1117 | t.Error("expected 4 to have been evicted") |
| 1118 | } |
| 1119 | if _, ok := cache.Get("5"); !ok { |
| 1120 | t.Error("expected 5 to exist") |
| 1121 | } |
| 1122 | } |