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