timeout_test.go 843 B

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. package fx
  2. import (
  3. "context"
  4. "testing"
  5. "time"
  6. "github.com/stretchr/testify/assert"
  7. )
  8. func TestWithPanic(t *testing.T) {
  9. assert.Panics(t, func() {
  10. _ = DoWithTimeout(func() error {
  11. panic("hello")
  12. }, time.Millisecond*50)
  13. })
  14. }
  15. func TestWithTimeout(t *testing.T) {
  16. assert.Equal(t, ErrTimeout, DoWithTimeout(func() error {
  17. time.Sleep(time.Millisecond * 50)
  18. return nil
  19. }, time.Millisecond))
  20. }
  21. func TestWithoutTimeout(t *testing.T) {
  22. assert.Nil(t, DoWithTimeout(func() error {
  23. return nil
  24. }, time.Millisecond*50))
  25. }
  26. func TestWithCancel(t *testing.T) {
  27. ctx, cancel := context.WithCancel(context.Background())
  28. go func() {
  29. time.Sleep(time.Millisecond * 10)
  30. cancel()
  31. }()
  32. err := DoWithTimeout(func() error {
  33. time.Sleep(time.Minute)
  34. return nil
  35. }, time.Second, WithContext(ctx))
  36. assert.Equal(t, ErrCanceled, err)
  37. }