enhancement wait utils.

This commit is contained in:
jolestar 2017-07-12 18:05:43 +08:00
parent 7d14bfa832
commit c122f02485
3 changed files with 18 additions and 2 deletions

View File

@ -15,7 +15,8 @@ func WaitJob(jobService *service.JobService, jobID string, timeout time.Duration
input := &service.DescribeJobsInput{Jobs: []*string{&jobID}} input := &service.DescribeJobsInput{Jobs: []*string{&jobID}}
output, err := jobService.DescribeJobs(input) output, err := jobService.DescribeJobs(input)
if err != nil { if err != nil {
return false, err //network or api error, not considered job fail.
return false, nil
} }
if len(output.JobSet) == 0 { if len(output.JobSet) == 0 {
return false, fmt.Errorf("Can not find job [%s]", jobID) return false, fmt.Errorf("Can not find job [%s]", jobID)

View File

@ -5,6 +5,18 @@ import (
"time" "time"
) )
// An Error represents a timeout error.
type TimeoutError struct {
timeout time.Duration
}
func (e *TimeoutError) Error() string { return fmt.Sprintf("Wait timeout [%s] ", e.timeout) }
func (e *TimeoutError) Timeout() time.Duration { return e.timeout }
func NewTimeoutError(timeout time.Duration) *TimeoutError {
return &TimeoutError{timeout: timeout}
}
// WaitForSpecificOrError wait a function return true or error. // WaitForSpecificOrError wait a function return true or error.
func WaitForSpecificOrError(f func() (bool, error), timeout time.Duration, waitInterval time.Duration) error { func WaitForSpecificOrError(f func() (bool, error), timeout time.Duration, waitInterval time.Duration) error {
ticker := time.NewTicker(waitInterval) ticker := time.NewTicker(waitInterval)
@ -23,7 +35,7 @@ func WaitForSpecificOrError(f func() (bool, error), timeout time.Duration, waitI
return nil return nil
} }
case <-timer.C: case <-timer.C:
return fmt.Errorf("Wait timeout [%s] ", timeout) return NewTimeoutError(timeout)
} }
} }
} }

View File

@ -42,5 +42,8 @@ func TestWaitForSpecificOrError(t *testing.T) {
return false, nil return false, nil
}, timeout, waitInterval) }, timeout, waitInterval)
assert.Error(t, err) assert.Error(t, err)
tErr, ok := err.(*TimeoutError)
assert.True(t, ok)
assert.Equal(t, timeout, tErr.timeout)
assert.Equal(t, 10, times) assert.Equal(t, 10, times)
} }