2018-05-27 07:02:29 -04:00
|
|
|
package task_test
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
"errors"
|
2019-02-02 16:19:30 -05:00
|
|
|
"strings"
|
2018-05-27 07:02:29 -04:00
|
|
|
"testing"
|
|
|
|
"time"
|
|
|
|
|
2019-02-02 16:19:30 -05:00
|
|
|
"github.com/google/go-cmp/cmp"
|
|
|
|
|
2021-02-16 15:31:50 -05:00
|
|
|
"github.com/v2fly/v2ray-core/v4/common"
|
|
|
|
. "github.com/v2fly/v2ray-core/v4/common/task"
|
2018-05-27 07:02:29 -04:00
|
|
|
)
|
|
|
|
|
|
|
|
func TestExecuteParallel(t *testing.T) {
|
2018-12-06 05:35:02 -05:00
|
|
|
err := Run(context.Background(),
|
|
|
|
func() error {
|
|
|
|
time.Sleep(time.Millisecond * 200)
|
|
|
|
return errors.New("test")
|
|
|
|
}, func() error {
|
|
|
|
time.Sleep(time.Millisecond * 500)
|
|
|
|
return errors.New("test2")
|
|
|
|
})
|
2018-05-27 07:02:29 -04:00
|
|
|
|
2019-02-02 16:19:30 -05:00
|
|
|
if r := cmp.Diff(err.Error(), "test"); r != "" {
|
|
|
|
t.Error(r)
|
|
|
|
}
|
2018-05-27 07:02:29 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
func TestExecuteParallelContextCancel(t *testing.T) {
|
|
|
|
ctx, cancel := context.WithCancel(context.Background())
|
2018-12-06 05:35:02 -05:00
|
|
|
err := Run(ctx, func() error {
|
2018-05-27 07:02:29 -04:00
|
|
|
time.Sleep(time.Millisecond * 2000)
|
|
|
|
return errors.New("test")
|
|
|
|
}, func() error {
|
|
|
|
time.Sleep(time.Millisecond * 5000)
|
|
|
|
return errors.New("test2")
|
|
|
|
}, func() error {
|
|
|
|
cancel()
|
|
|
|
return nil
|
2018-12-06 05:35:02 -05:00
|
|
|
})
|
2018-05-27 07:02:29 -04:00
|
|
|
|
2019-02-02 16:19:30 -05:00
|
|
|
errStr := err.Error()
|
|
|
|
if !strings.Contains(errStr, "canceled") {
|
|
|
|
t.Error("expected error string to contain 'canceled', but actually not: ", errStr)
|
|
|
|
}
|
2018-05-27 07:02:29 -04:00
|
|
|
}
|
2018-11-14 15:00:51 -05:00
|
|
|
|
|
|
|
func BenchmarkExecuteOne(b *testing.B) {
|
|
|
|
noop := func() error {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
for i := 0; i < b.N; i++ {
|
2018-12-06 05:35:02 -05:00
|
|
|
common.Must(Run(context.Background(), noop))
|
2018-11-14 15:00:51 -05:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func BenchmarkExecuteTwo(b *testing.B) {
|
|
|
|
noop := func() error {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
for i := 0; i < b.N; i++ {
|
2018-12-06 05:35:02 -05:00
|
|
|
common.Must(Run(context.Background(), noop, noop))
|
2018-11-14 15:00:51 -05:00
|
|
|
}
|
|
|
|
}
|