package util

import (
	"context"
	"math/rand"
	"sync"
	"sync/atomic"
	"testing"
	"time"

	"github.com/stretchr/testify/require"
)

func TestSimpleWorkerPool(t *testing.T) {
	startTime := time.Now()
	rand.Seed(startTime.UnixNano())
	var total int32
	var wg sync.WaitGroup
	fn := func(ctx context.Context) {
		defer wg.Done()
		time.Sleep(time.Duration(rand.Intn(300)+200) * time.Millisecond)
		atomic.AddInt32(&total, 1)
	}

	threadPool := NewSimpleWorkerPool(5)
	for i := 0; i < 10; i++ {
		wg.Add(1)
		threadPool.Apply(context.Background(), fn)
	}

	wg.Wait()
	require.Equal(t, int32(10), total)
	require.Less(t, time.Since(startTime), time.Second*2)
}
