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

77 lines
1.4 KiB
Go
Raw Normal View History

2020-05-03 05:53:23 +03:00
package deadline
import (
"errors"
2020-06-05 12:36:30 +03:00
"fmt"
2020-05-03 05:53:23 +03:00
"testing"
"time"
)
2020-06-05 12:36:30 +03:00
func workerTakes5ms(stopper chan error) error {
fmt.Println("i'm doing this job in 5ms")
2020-05-03 05:53:23 +03:00
time.Sleep(5 * time.Millisecond)
return nil
}
2020-06-05 12:36:30 +03:00
func workerTakes20ms(stopper chan error) error {
fmt.Println("i'm doing this job in 20ms,so work will timeout")
2020-05-03 05:53:23 +03:00
time.Sleep(20 * time.Millisecond)
return nil
}
2020-06-05 12:36:30 +03:00
func cancelWork(stopper chan error) error {
fmt.Println("i'm doing this job")
stopper <- errors.New("canceled job") //cancel job
time.Sleep(5 * time.Millisecond)
fmt.Println("job canceled")
return nil
}
func returnsError(stopper chan error) error {
fmt.Println("i'm doing this job but error occurred")
2020-05-03 05:53:23 +03:00
return errors.New("foo")
}
2020-06-05 07:57:11 +03:00
func TestMultiDeadline(t *testing.T) {
2020-05-03 05:53:23 +03:00
2020-06-05 12:36:30 +03:00
dl := New(15*time.Millisecond, "test multi deadline case")
2020-05-03 05:53:23 +03:00
2020-06-05 12:36:30 +03:00
if err := dl.Run(workerTakes5ms); err != nil {
2020-05-03 05:53:23 +03:00
t.Error(err)
}
2020-06-05 12:36:30 +03:00
err := dl.Run(cancelWork)
t.Log("cancelWork error:", err)
if err.Error() != "canceled job" {
2020-05-03 05:53:23 +03:00
t.Error(err)
}
2020-06-05 12:36:30 +03:00
err = dl.Run(workerTakes20ms)
2020-05-03 05:53:23 +03:00
if err != ErrTimedOut {
t.Error(err)
}
}
2020-06-05 07:57:11 +03:00
func TestDeadline(t *testing.T) {
2020-05-03 05:53:23 +03:00
2020-06-05 12:36:30 +03:00
dl := New(1*time.Second, "one time deadline case worker")
done := make(chan error)
err := dl.Run(func(stopper chan error) error {
fmt.Println("i am doing something here")
time.Sleep(time.Second * 2)
close(done)
2020-05-03 05:53:23 +03:00
return nil
})
2020-06-05 12:36:30 +03:00
if err != ErrTimedOut {
t.Error(err)
2020-05-03 05:53:23 +03:00
}
2020-06-05 12:36:30 +03:00
<-done
2020-05-03 05:53:23 +03:00
}