go-pattern-examples/resiliency/03_deadline/deadline_test.go

66 lines
1.1 KiB
Go
Raw Normal View History

2020-05-03 05:53:23 +03:00
package deadline
import (
"errors"
"testing"
"time"
)
2020-06-05 07:57:11 +03:00
func takes5ms(stopper <-chan struct{}) error {
2020-05-03 05:53:23 +03:00
time.Sleep(5 * time.Millisecond)
return nil
}
2020-06-05 07:57:11 +03:00
func takes20ms(stopper <-chan struct{}) error {
2020-05-03 05:53:23 +03:00
time.Sleep(20 * time.Millisecond)
return nil
}
func returnsError(stopper <-chan struct{}) error {
return errors.New("foo")
}
2020-06-05 07:57:11 +03:00
func TestMultiDeadline(t *testing.T) {
dl := New(10*time.Millisecond, "test multi deadline case")
2020-05-03 05:53:23 +03:00
2020-06-05 07:57:11 +03:00
if err := dl.Run(takes5ms); err != nil {
2020-05-03 05:53:23 +03:00
t.Error(err)
}
2020-06-05 07:57:11 +03:00
if err := dl.Run(takes20ms); err != ErrTimedOut {
2020-05-03 05:53:23 +03:00
t.Error(err)
}
if err := dl.Run(returnsError); err.Error() != "foo" {
t.Error(err)
}
done := make(chan struct{})
err := dl.Run(func(stopper <-chan struct{}) error {
<-stopper
close(done)
return nil
})
if err != ErrTimedOut {
t.Error(err)
}
<-done
}
2020-06-05 07:57:11 +03:00
func TestDeadline(t *testing.T) {
dl := New(1*time.Second, "one dead line case")
2020-05-03 05:53:23 +03:00
err := dl.Run(func(stopper <-chan struct{}) error {
2020-06-05 07:57:11 +03:00
time.Sleep(time.Second * 10)
2020-05-03 05:53:23 +03:00
return nil
})
switch err {
case ErrTimedOut:
2020-06-05 07:57:11 +03:00
t.Error("execution took too long, oops")
2020-05-03 05:53:23 +03:00
default:
// some other error
2020-06-05 07:57:11 +03:00
t.Log("done")
2020-05-03 05:53:23 +03:00
}
}