github.com/jxskiss/gopkg@v0.17.3/retry/retry_test.go (about) 1 package retry 2 3 import ( 4 "fmt" 5 "testing" 6 "time" 7 8 "github.com/stretchr/testify/assert" 9 ) 10 11 func Test_Retry(t *testing.T) { 12 is := assert.New(t) 13 target := fakeErrors(3) 14 15 begin := time.Now() 16 r := Retry(3, 100*time.Millisecond, target) 17 cost := time.Since(begin) 18 is.True(!r.Ok) 19 is.Equal(r.Attempts, 3) 20 is.True(cost > 150*time.Millisecond) 21 is.True(cost < 450*time.Millisecond) 22 23 merr, ok := r.Error.(*sizedError) 24 is.True(ok) 25 merrors := merr.Errors() 26 is.Equal(len(merrors), 3) 27 is.Equal(merrors[0].Error(), "error 3") 28 is.Equal(merrors[1].Error(), "error 2") 29 is.Equal(merrors[2].Error(), "error 1") 30 31 target = fakeErrors(3) 32 begin = time.Now() 33 r = Retry(5, 100*time.Millisecond, target) 34 cost = time.Since(begin) 35 is.True(r.Ok) 36 is.Equal(r.Attempts, 4) 37 is.True(cost > 350*time.Millisecond) 38 is.True(cost < 1050*time.Millisecond) 39 40 merr, ok = r.Error.(*sizedError) 41 is.True(ok) 42 merrors = merr.Errors() 43 is.Equal(len(merrors), 3) 44 is.Equal(merrors[0].Error(), "error 3") 45 is.Equal(merrors[1].Error(), "error 2") 46 is.Equal(merrors[2].Error(), "error 1") 47 } 48 49 func Test_Hook(t *testing.T) { 50 is := assert.New(t) 51 target := fakeErrors(3) 52 hook := &fakeHook{} 53 54 r := Retry(5, time.Millisecond, target, Hook(hook.log)) 55 is.True(r.Ok) 56 is.Equal(hook.attempts, 3) 57 is.Equal(len(hook.errs), 3) 58 is.Equal(hook.errs[0], "error 1") 59 is.Equal(hook.errs[1], "error 2") 60 is.Equal(hook.errs[2], "error 3") 61 } 62 63 func fakeErrors(errCount int) func() error { 64 attempt := 0 65 return func() error { 66 attempt++ 67 if attempt <= errCount { 68 return fmt.Errorf("error %d", attempt) 69 } 70 return nil 71 } 72 } 73 74 type fakeHook struct { 75 attempts int 76 errs []string 77 } 78 79 func (h *fakeHook) log(attempts int, err error) { 80 h.attempts = attempts 81 h.errs = append(h.errs, err.Error()) 82 }