From e147a41f928241f8497ead40d6aada293cd6255d Mon Sep 17 00:00:00 2001 From: Philipp Heckel Date: Wed, 16 Nov 2022 10:44:10 -0500 Subject: [PATCH] Fix race in tests --- util/batching_queue_test.go | 20 +++++++++++++------- 1 file changed, 13 insertions(+), 7 deletions(-) diff --git a/util/batching_queue_test.go b/util/batching_queue_test.go index 28764f18..f7dccfab 100644 --- a/util/batching_queue_test.go +++ b/util/batching_queue_test.go @@ -1,40 +1,46 @@ package util_test import ( - "fmt" "github.com/stretchr/testify/require" "heckel.io/ntfy/util" "math/rand" + "sync" "testing" "time" ) func TestBatchingQueue_InfTimeout(t *testing.T) { q := util.NewBatchingQueue[int](25, 1*time.Hour) - batches := make([][]int, 0) - total := 0 + batches, total := make([][]int, 0), 0 + var mu sync.Mutex go func() { for batch := range q.Dequeue() { + mu.Lock() batches = append(batches, batch) total += len(batch) + mu.Unlock() } }() for i := 0; i < 101; i++ { go q.Enqueue(i) } time.Sleep(500 * time.Millisecond) + mu.Lock() require.Equal(t, 100, total) // One is missing, stuck in the last batch! require.Equal(t, 4, len(batches)) + mu.Unlock() } func TestBatchingQueue_WithTimeout(t *testing.T) { q := util.NewBatchingQueue[int](25, 100*time.Millisecond) - batches := make([][]int, 0) - total := 0 + batches, total := make([][]int, 0), 0 + var mu sync.Mutex go func() { for batch := range q.Dequeue() { + mu.Lock() batches = append(batches, batch) total += len(batch) + mu.Unlock() } }() for i := 0; i < 101; i++ { @@ -44,9 +50,9 @@ func TestBatchingQueue_WithTimeout(t *testing.T) { }(i) } time.Sleep(time.Second) - fmt.Println(len(batches)) - fmt.Println(batches) + mu.Lock() require.Equal(t, 101, total) require.True(t, len(batches) > 4) // 101/25 require.True(t, len(batches) < 21) + mu.Unlock() }