ntfy/util/batching_queue_test.go

59 lines
1.2 KiB
Go
Raw Normal View History

2022-11-15 20:24:56 +01:00
package util_test
import (
2022-11-16 16:28:20 +01:00
"github.com/stretchr/testify/require"
2022-11-15 20:24:56 +01:00
"heckel.io/ntfy/util"
"math/rand"
2022-11-16 16:44:10 +01:00
"sync"
2022-11-15 20:24:56 +01:00
"testing"
"time"
)
2022-11-16 16:28:20 +01:00
func TestBatchingQueue_InfTimeout(t *testing.T) {
q := util.NewBatchingQueue[int](25, 1*time.Hour)
2022-11-16 16:44:10 +01:00
batches, total := make([][]int, 0), 0
var mu sync.Mutex
2022-11-15 20:24:56 +01:00
go func() {
2022-11-16 16:28:20 +01:00
for batch := range q.Dequeue() {
2022-11-16 16:44:10 +01:00
mu.Lock()
2022-11-16 16:28:20 +01:00
batches = append(batches, batch)
total += len(batch)
2022-11-16 16:44:10 +01:00
mu.Unlock()
2022-11-15 20:24:56 +01:00
}
}()
2022-11-16 16:28:20 +01:00
for i := 0; i < 101; i++ {
go q.Enqueue(i)
}
time.Sleep(500 * time.Millisecond)
2022-11-16 16:44:10 +01:00
mu.Lock()
2022-11-16 16:28:20 +01:00
require.Equal(t, 100, total) // One is missing, stuck in the last batch!
require.Equal(t, 4, len(batches))
2022-11-16 16:44:10 +01:00
mu.Unlock()
2022-11-16 16:28:20 +01:00
}
func TestBatchingQueue_WithTimeout(t *testing.T) {
q := util.NewBatchingQueue[int](25, 100*time.Millisecond)
2022-11-16 16:44:10 +01:00
batches, total := make([][]int, 0), 0
var mu sync.Mutex
2022-11-16 16:28:20 +01:00
go func() {
for batch := range q.Dequeue() {
2022-11-16 16:44:10 +01:00
mu.Lock()
2022-11-16 16:28:20 +01:00
batches = append(batches, batch)
total += len(batch)
2022-11-16 16:44:10 +01:00
mu.Unlock()
2022-11-16 16:28:20 +01:00
}
}()
for i := 0; i < 101; i++ {
2022-11-15 20:24:56 +01:00
go func(i int) {
2022-11-16 16:28:20 +01:00
time.Sleep(time.Duration(rand.Intn(700)) * time.Millisecond)
q.Enqueue(i)
2022-11-15 20:24:56 +01:00
}(i)
}
2022-11-16 16:28:20 +01:00
time.Sleep(time.Second)
2022-11-16 16:44:10 +01:00
mu.Lock()
2022-11-16 16:28:20 +01:00
require.Equal(t, 101, total)
require.True(t, len(batches) > 4) // 101/25
require.True(t, len(batches) < 21)
2022-11-16 16:44:10 +01:00
mu.Unlock()
2022-11-15 20:24:56 +01:00
}