task_test.go 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  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(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. assert(err.Error(), Equals, "test")
  22. }
  23. func TestExecuteParallelContextCancel(t *testing.T) {
  24. assert := With(t)
  25. ctx, cancel := context.WithCancel(context.Background())
  26. err := Run(ctx, func() error {
  27. time.Sleep(time.Millisecond * 2000)
  28. return errors.New("test")
  29. }, func() error {
  30. time.Sleep(time.Millisecond * 5000)
  31. return errors.New("test2")
  32. }, func() error {
  33. cancel()
  34. return nil
  35. })
  36. assert(err.Error(), HasSubstring, "canceled")
  37. }
  38. func BenchmarkExecuteOne(b *testing.B) {
  39. noop := func() error {
  40. return nil
  41. }
  42. for i := 0; i < b.N; i++ {
  43. common.Must(Run(context.Background(), noop))
  44. }
  45. }
  46. func BenchmarkExecuteTwo(b *testing.B) {
  47. noop := func() error {
  48. return nil
  49. }
  50. for i := 0; i < b.N; i++ {
  51. common.Must(Run(context.Background(), noop, noop))
  52. }
  53. }