2022-11-15 20:24:56 +01:00
|
|
|
package util_test
|
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
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"
|
|
|
|
"testing"
|
|
|
|
"time"
|
|
|
|
)
|
|
|
|
|
2022-11-16 16:28:20 +01:00
|
|
|
func TestBatchingQueue_InfTimeout(t *testing.T) {
|
|
|
|
q := util.NewBatchingQueue[int](25, 1*time.Hour)
|
|
|
|
batches := make([][]int, 0)
|
|
|
|
total := 0
|
2022-11-15 20:24:56 +01:00
|
|
|
go func() {
|
2022-11-16 16:28:20 +01:00
|
|
|
for batch := range q.Dequeue() {
|
|
|
|
batches = append(batches, batch)
|
|
|
|
total += len(batch)
|
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)
|
|
|
|
require.Equal(t, 100, total) // One is missing, stuck in the last batch!
|
|
|
|
require.Equal(t, 4, len(batches))
|
|
|
|
}
|
|
|
|
|
|
|
|
func TestBatchingQueue_WithTimeout(t *testing.T) {
|
|
|
|
q := util.NewBatchingQueue[int](25, 100*time.Millisecond)
|
|
|
|
batches := make([][]int, 0)
|
|
|
|
total := 0
|
|
|
|
go func() {
|
|
|
|
for batch := range q.Dequeue() {
|
|
|
|
batches = append(batches, batch)
|
|
|
|
total += len(batch)
|
|
|
|
}
|
|
|
|
}()
|
|
|
|
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)
|
|
|
|
fmt.Println(len(batches))
|
|
|
|
fmt.Println(batches)
|
|
|
|
require.Equal(t, 101, total)
|
|
|
|
require.True(t, len(batches) > 4) // 101/25
|
|
|
|
require.True(t, len(batches) < 21)
|
2022-11-15 20:24:56 +01:00
|
|
|
}
|