deadline_test.go 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. package deadline
  2. import (
  3. "errors"
  4. "testing"
  5. "time"
  6. )
  7. func takesFiveMillis(stopper <-chan struct{}) error {
  8. time.Sleep(5 * time.Millisecond)
  9. return nil
  10. }
  11. func takesTwentyMillis(stopper <-chan struct{}) error {
  12. time.Sleep(20 * time.Millisecond)
  13. return nil
  14. }
  15. func returnsError(stopper <-chan struct{}) error {
  16. return errors.New("foo")
  17. }
  18. func TestDeadline(t *testing.T) {
  19. dl := New(10 * time.Millisecond)
  20. if err := dl.Run(takesFiveMillis); err != nil {
  21. t.Error(err)
  22. }
  23. if err := dl.Run(takesTwentyMillis); err != ErrTimedOut {
  24. t.Error(err)
  25. }
  26. if err := dl.Run(returnsError); err.Error() != "foo" {
  27. t.Error(err)
  28. }
  29. done := make(chan struct{})
  30. err := dl.Run(func(stopper <-chan struct{}) error {
  31. <-stopper
  32. close(done)
  33. return nil
  34. })
  35. if err != ErrTimedOut {
  36. t.Error(err)
  37. }
  38. <-done
  39. }
  40. func ExampleDeadline() {
  41. dl := New(1 * time.Second)
  42. err := dl.Run(func(stopper <-chan struct{}) error {
  43. // do something possibly slow
  44. // check stopper function and give up if timed out
  45. return nil
  46. })
  47. switch err {
  48. case ErrTimedOut:
  49. // execution took too long, oops
  50. default:
  51. // some other error
  52. }
  53. }