github.com/fufuok/freelru@v0.13.3/syncedlru_test.go (about) 1 // nolint: dupl 2 package freelru 3 4 import ( 5 "sync" 6 "testing" 7 "time" 8 ) 9 10 // TestSyncedRaceCondition tests that the synced LRU is safe to use concurrently. 11 // Test with 'go test . -race'. 12 func TestSyncedRaceCondition(t *testing.T) { 13 const CAP = 4 14 15 lru, err := NewSyncedDefault[uint64, int](CAP) 16 if err != nil { 17 t.Fatalf("err: %v", err) 18 } 19 20 wg := sync.WaitGroup{} 21 22 call := func(fn func()) { 23 wg.Add(1) 24 go func() { 25 fn() 26 wg.Done() 27 }() 28 } 29 30 call(func() { lru.SetLifetime(0) }) 31 call(func() { lru.SetOnEvict(nil) }) 32 call(func() { _ = lru.Len() }) 33 call(func() { _ = lru.AddWithLifetime(1, 1, 0) }) 34 call(func() { _ = lru.Add(1, 1) }) 35 call(func() { _, _ = lru.Get(1) }) 36 call(func() { _, _ = lru.Peek(1) }) 37 call(func() { _ = lru.Contains(1) }) 38 call(func() { _ = lru.Remove(1) }) 39 call(func() { _ = lru.Keys() }) 40 call(func() { lru.Purge() }) 41 call(func() { lru.Metrics() }) 42 call(func() { _ = lru.ResetMetrics() }) 43 call(func() { lru.dump() }) 44 call(func() { lru.PrintStats() }) 45 46 wg.Wait() 47 } 48 49 func TestSyncedLRUMetrics(t *testing.T) { 50 cache, _ := NewSyncedDefault[uint64, uint64](1) 51 testMetrics(t, cache) 52 53 lru, _ := NewSyncedDefault[string, struct{}](5, time.Second*5) 54 m := lru.Metrics() 55 FatalIf(t, m.Capacity != 5, "Unexpected capacity: %d (!= %d)", m.Capacity, 5) 56 FatalIf(t, m.Lifetime != "5s", "Unexpected lifetime: %s (!= %s)", m.Lifetime, "5s") 57 58 lru.ResetMetrics() 59 m = lru.Metrics() 60 FatalIf(t, m.Capacity != 5, "Unexpected capacity: %d (!= %d)", m.Capacity, 5) 61 FatalIf(t, m.Lifetime != "5s", "Unexpected lifetime: %s (!= %s)", m.Lifetime, "5s") 62 }