task_test.go 1.3 KB

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