| 1 |
package util_test |
| 2 |
|
| 3 |
import ( |
| 4 |
"github.com/stretchr/testify/require" |
| 5 |
"heckel.io/ntfy/v2/util" |
| 6 |
"math/rand" |
| 7 |
"sync" |
| 8 |
"testing" |
| 9 |
"time" |
| 10 |
) |
| 11 |
|
| 12 |
func TestBatchingQueue_InfTimeout(t *testing.T) { |
| 13 |
q := util.NewBatchingQueue[int](25, 1*time.Hour) |
| 14 |
batches, total := make([][]int, 0), 0 |
| 15 |
var mu sync.Mutex |
| 16 |
go func() { |
| 17 |
for batch := range q.Dequeue() { |
| 18 |
mu.Lock() |
| 19 |
batches = append(batches, batch) |
| 20 |
total += len(batch) |
| 21 |
mu.Unlock() |
| 22 |
} |
| 23 |
}() |
| 24 |
for i := 0; i < 101; i++ { |
| 25 |
go q.Enqueue(i) |
| 26 |
} |
| 27 |
time.Sleep(time.Second) |
| 28 |
mu.Lock() |
| 29 |
require.Equal(t, 100, total) // One is missing, stuck in the last batch! |
| 30 |
require.Equal(t, 4, len(batches)) |
| 31 |
mu.Unlock() |
| 32 |
} |
| 33 |
|
| 34 |
func TestBatchingQueue_WithTimeout(t *testing.T) { |
| 35 |
q := util.NewBatchingQueue[int](25, 100*time.Millisecond) |
| 36 |
batches, total := make([][]int, 0), 0 |
| 37 |
var mu sync.Mutex |
| 38 |
go func() { |
| 39 |
for batch := range q.Dequeue() { |
| 40 |
mu.Lock() |
| 41 |
batches = append(batches, batch) |
| 42 |
total += len(batch) |
| 43 |
mu.Unlock() |
| 44 |
} |
| 45 |
}() |
| 46 |
for i := 0; i < 101; i++ { |
| 47 |
go func(i int) { |
| 48 |
time.Sleep(time.Duration(rand.Intn(700)) * time.Millisecond) |
| 49 |
q.Enqueue(i) |
| 50 |
}(i) |
| 51 |
} |
| 52 |
time.Sleep(time.Second) |
| 53 |
mu.Lock() |
| 54 |
require.Equal(t, 101, total) |
| 55 |
require.True(t, len(batches) > 4) // 101/25 |
| 56 |
require.True(t, len(batches) < 21) |
| 57 |
mu.Unlock() |
| 58 |
} |