github.com/xraypb/xray-core@v1.6.6/common/task/task_test.go (about)

     1  package task_test
     2  
     3  import (
     4  	"context"
     5  	"errors"
     6  	"strings"
     7  	"testing"
     8  	"time"
     9  
    10  	"github.com/google/go-cmp/cmp"
    11  	"github.com/xraypb/xray-core/common"
    12  	. "github.com/xraypb/xray-core/common/task"
    13  )
    14  
    15  func TestExecuteParallel(t *testing.T) {
    16  	err := Run(context.Background(),
    17  		func() error {
    18  			time.Sleep(time.Millisecond * 200)
    19  			return errors.New("test")
    20  		}, func() error {
    21  			time.Sleep(time.Millisecond * 500)
    22  			return errors.New("test2")
    23  		})
    24  
    25  	if r := cmp.Diff(err.Error(), "test"); r != "" {
    26  		t.Error(r)
    27  	}
    28  }
    29  
    30  func TestExecuteParallelContextCancel(t *testing.T) {
    31  	ctx, cancel := context.WithCancel(context.Background())
    32  	err := Run(ctx, func() error {
    33  		time.Sleep(time.Millisecond * 2000)
    34  		return errors.New("test")
    35  	}, func() error {
    36  		time.Sleep(time.Millisecond * 5000)
    37  		return errors.New("test2")
    38  	}, func() error {
    39  		cancel()
    40  		return nil
    41  	})
    42  
    43  	errStr := err.Error()
    44  	if !strings.Contains(errStr, "canceled") {
    45  		t.Error("expected error string to contain 'canceled', but actually not: ", errStr)
    46  	}
    47  }
    48  
    49  func BenchmarkExecuteOne(b *testing.B) {
    50  	noop := func() error {
    51  		return nil
    52  	}
    53  	for i := 0; i < b.N; i++ {
    54  		common.Must(Run(context.Background(), noop))
    55  	}
    56  }
    57  
    58  func BenchmarkExecuteTwo(b *testing.B) {
    59  	noop := func() error {
    60  		return nil
    61  	}
    62  	for i := 0; i < b.N; i++ {
    63  		common.Must(Run(context.Background(), noop, noop))
    64  	}
    65  }