Skip to content

Commit f887fed

Browse files
committed
fixed a data race issue with test code
1 parent e242d69 commit f887fed

File tree

1 file changed

+20
-6
lines changed

1 file changed

+20
-6
lines changed

sieve/sieve_test.go

Lines changed: 20 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
package sieve
22

33
import (
4+
"sync"
45
"testing"
56
"time"
67

@@ -166,22 +167,35 @@ func TestEvictionCallback(t *testing.T) {
166167
}
167168

168169
func TestEvictionCallbackWithTTL(t *testing.T) {
170+
var mu sync.Mutex
169171
cache := New[int, int](10, time.Second)
170172
evicted := make(map[int]int)
171173
cache.SetOnEvict(func(key int, value int) {
174+
mu.Lock()
172175
evicted[key] = value
176+
mu.Unlock()
173177
})
174178

175179
// add objects to the cache
176180
for i := 1; i <= 10; i++ {
177181
cache.Set(i, i)
178182
}
179183

180-
// wait for the objects to be evicted
181-
time.Sleep(time.Second * 2)
182-
183-
// check the callback received all the evicted objects
184-
for i := 1; i <= 10; i++ {
185-
require.Equal(t, i, evicted[i])
184+
timeout := time.After(5 * time.Second)
185+
ticker := time.NewTicker(100 * time.Millisecond)
186+
for {
187+
select {
188+
case <-timeout:
189+
t.Fatal("timeout")
190+
case <-ticker.C:
191+
mu.Lock()
192+
if len(evicted) == 10 {
193+
for i := 1; i <= 10; i++ {
194+
require.Equal(t, i, evicted[i])
195+
}
196+
return
197+
}
198+
mu.Unlock()
199+
}
186200
}
187201
}

0 commit comments

Comments
 (0)