github.com/go-board/x-go@v0.1.2-0.20220610024734-db1323f6cb15/concurrent/executor_test.go (about)

     1  package concurrent_test
     2  
     3  import (
     4  	"context"
     5  	"testing"
     6  	"time"
     7  
     8  	"github.com/stretchr/testify/require"
     9  
    10  	"github.com/go-board/x-go/concurrent"
    11  )
    12  
    13  func TestPool(t *testing.T) {
    14  	t.Run("spawn", func(t *testing.T) {
    15  		p := concurrent.NewPool(1, 10)
    16  		now := time.Now()
    17  		task := p.Spawn(context.Background(), func(ctx context.Context) error {
    18  			time.Sleep(time.Second)
    19  			return nil
    20  		})
    21  		err := task.Wait()
    22  		require.Nil(t, err, "err must be nil")
    23  		require.Equal(t, 1, int(time.Since(now).Seconds()), "task spent 1 second")
    24  	})
    25  	t.Run("spawn timeout", func(t *testing.T) {
    26  		p := concurrent.NewPool(1, 10)
    27  		now := time.Now()
    28  		task := p.Spawn(context.Background(), func(ctx context.Context) error {
    29  			time.Sleep(time.Second * 2)
    30  			return nil
    31  		})
    32  		err := task.WaitTimeout(time.Second)
    33  		require.NotNil(t, err, "err must be not nil")
    34  		require.Equal(t, 1, int(time.Since(now).Seconds()), "task spent 1 second")
    35  	})
    36  }