task_test.go 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. package task_test
  2. import (
  3. "context"
  4. "errors"
  5. "testing"
  6. "time"
  7. "v2ray.com/core/common"
  8. . "v2ray.com/core/common/task"
  9. . "v2ray.com/ext/assert"
  10. )
  11. func TestExecuteParallel(t *testing.T) {
  12. assert := With(t)
  13. err := Run(Parallel(func() error {
  14. time.Sleep(time.Millisecond * 200)
  15. return errors.New("test")
  16. }, func() error {
  17. time.Sleep(time.Millisecond * 500)
  18. return errors.New("test2")
  19. }))()
  20. assert(err.Error(), Equals, "test")
  21. }
  22. func TestExecuteParallelContextCancel(t *testing.T) {
  23. assert := With(t)
  24. ctx, cancel := context.WithCancel(context.Background())
  25. err := Run(WithContext(ctx), Parallel(func() error {
  26. time.Sleep(time.Millisecond * 2000)
  27. return errors.New("test")
  28. }, func() error {
  29. time.Sleep(time.Millisecond * 5000)
  30. return errors.New("test2")
  31. }, func() error {
  32. cancel()
  33. return nil
  34. }))()
  35. assert(err.Error(), HasSubstring, "canceled")
  36. }
  37. func BenchmarkExecuteOne(b *testing.B) {
  38. noop := func() error {
  39. return nil
  40. }
  41. for i := 0; i < b.N; i++ {
  42. common.Must(Run(Parallel(noop))())
  43. }
  44. }
  45. func BenchmarkExecuteTwo(b *testing.B) {
  46. noop := func() error {
  47. return nil
  48. }
  49. for i := 0; i < b.N; i++ {
  50. common.Must(Run(Parallel(noop, noop))())
  51. }
  52. }
  53. func BenchmarkExecuteContext(b *testing.B) {
  54. noop := func() error {
  55. return nil
  56. }
  57. background := context.Background()
  58. for i := 0; i < b.N; i++ {
  59. common.Must(Run(WithContext(background), Parallel(noop, noop))())
  60. }
  61. }