From 01b70a248e7a48b0249cf193c7efe7eff2e78767 Mon Sep 17 00:00:00 2001 From: Artem Poltorzhitskiy Date: Wed, 3 Jul 2024 12:52:55 +0200 Subject: [PATCH] Test: ttl cache multi-threading (#235) --- cmd/api/cache/ttl_test.go | 39 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) diff --git a/cmd/api/cache/ttl_test.go b/cmd/api/cache/ttl_test.go index afac69a4..a7e5ffe2 100644 --- a/cmd/api/cache/ttl_test.go +++ b/cmd/api/cache/ttl_test.go @@ -4,7 +4,9 @@ package cache import ( + "crypto/rand" "fmt" + "math/big" "sync" "testing" "time" @@ -118,6 +120,43 @@ func TestTTLCache_SetGet(t *testing.T) { require.Len(t, c.queue, 4) require.Len(t, c.m, 3) }) + + t.Run("multithread", func(t *testing.T) { + c := NewTTLCache(Config{MaxEntitiesCount: 10}, time.Millisecond) + + var wg sync.WaitGroup + set := func(wg *sync.WaitGroup) { + wg.Done() + + for i := 0; i < 100; i++ { + val, err := rand.Int(rand.Reader, big.NewInt(255)) + require.NoError(t, err) + c.Set(val.String(), []byte{byte(i)}) + } + } + get := func(wg *sync.WaitGroup) { + wg.Done() + + for i := 0; i < 100; i++ { + c.Get(fmt.Sprintf("%d", i)) + } + } + + for i := 0; i < 100; i++ { + wg.Add(2) + set(&wg) + get(&wg) + } + + wg.Wait() + + require.Len(t, c.queue, 10) + require.Len(t, c.m, 10) + + for key := range c.m { + require.Contains(t, c.queue, key) + } + }) } func TestTTLCache_Clear(t *testing.T) {