github.com/igoogolx/clash@v1.19.8/common/batch/batch_test.go (about)

     1  package batch
     2  
     3  import (
     4  	"context"
     5  	"errors"
     6  	"strconv"
     7  	"testing"
     8  	"time"
     9  
    10  	"github.com/stretchr/testify/assert"
    11  )
    12  
    13  func TestBatch(t *testing.T) {
    14  	b, _ := New(context.Background())
    15  
    16  	now := time.Now()
    17  	b.Go("foo", func() (any, error) {
    18  		time.Sleep(time.Millisecond * 100)
    19  		return "foo", nil
    20  	})
    21  	b.Go("bar", func() (any, error) {
    22  		time.Sleep(time.Millisecond * 150)
    23  		return "bar", nil
    24  	})
    25  	result, err := b.WaitAndGetResult()
    26  
    27  	assert.Nil(t, err)
    28  
    29  	duration := time.Since(now)
    30  	assert.Less(t, duration, time.Millisecond*200)
    31  	assert.Equal(t, 2, len(result))
    32  
    33  	for k, v := range result {
    34  		assert.NoError(t, v.Err)
    35  		assert.Equal(t, k, v.Value.(string))
    36  	}
    37  }
    38  
    39  func TestBatchWithConcurrencyNum(t *testing.T) {
    40  	b, _ := New(
    41  		context.Background(),
    42  		WithConcurrencyNum(3),
    43  	)
    44  
    45  	now := time.Now()
    46  	for i := 0; i < 7; i++ {
    47  		idx := i
    48  		b.Go(strconv.Itoa(idx), func() (any, error) {
    49  			time.Sleep(time.Millisecond * 100)
    50  			return strconv.Itoa(idx), nil
    51  		})
    52  	}
    53  	result, _ := b.WaitAndGetResult()
    54  	duration := time.Since(now)
    55  	assert.Greater(t, duration, time.Millisecond*260)
    56  	assert.Equal(t, 7, len(result))
    57  
    58  	for k, v := range result {
    59  		assert.NoError(t, v.Err)
    60  		assert.Equal(t, k, v.Value.(string))
    61  	}
    62  }
    63  
    64  func TestBatchContext(t *testing.T) {
    65  	b, ctx := New(context.Background())
    66  
    67  	b.Go("error", func() (any, error) {
    68  		time.Sleep(time.Millisecond * 100)
    69  		return nil, errors.New("test error")
    70  	})
    71  
    72  	b.Go("ctx", func() (any, error) {
    73  		<-ctx.Done()
    74  		return nil, ctx.Err()
    75  	})
    76  
    77  	result, err := b.WaitAndGetResult()
    78  
    79  	assert.NotNil(t, err)
    80  	assert.Equal(t, "error", err.Key)
    81  
    82  	assert.Equal(t, ctx.Err(), result["ctx"].Err)
    83  }