github.com/sohaha/zlsgo@v1.7.13-0.20240501141223-10dd1a906f76/zutil/retry_test.go (about) 1 package zutil 2 3 import ( 4 "testing" 5 "time" 6 7 "github.com/sohaha/zlsgo" 8 ) 9 10 func TestRetry(tt *testing.T) { 11 t := zlsgo.NewTest(tt) 12 13 t.Run("Success", func(t *zlsgo.TestUtil) { 14 i := 0 15 now := time.Now() 16 ok := DoRetry(5, func() bool { 17 if i < 3 { 18 i++ 19 return false 20 } 21 return true 22 }, func(rc *RetryConf) { 23 rc.Interval = time.Second / 5 24 }) 25 t.EqualTrue(ok) 26 t.EqualTrue(time.Since(now).Seconds() < 1) 27 t.Equal(3, i) 28 }) 29 30 t.Run("Success BackOffDelay", func(t *zlsgo.TestUtil) { 31 i := 0 32 now := time.Now() 33 ok := DoRetry(5, func() bool { 34 if i < 3 { 35 i++ 36 return false 37 } 38 return true 39 }, func(rc *RetryConf) { 40 rc.BackOffDelay = true 41 rc.Interval = time.Second / 5 42 }) 43 t.EqualTrue(ok) 44 t.EqualTrue(time.Since(now).Seconds() < 6) 45 t.EqualTrue(time.Since(now).Seconds() > 2) 46 t.Equal(3, i) 47 }) 48 49 t.Run("Failed", func(t *zlsgo.TestUtil) { 50 i := 0 51 now := time.Now() 52 ok := DoRetry(5, func() bool { 53 i++ 54 return false 55 }, func(rc *RetryConf) { 56 rc.Interval = time.Second / 5 57 }) 58 t.EqualTrue(!ok) 59 t.EqualTrue(time.Since(now).Seconds() > 1) 60 t.Equal(6, i) 61 }) 62 63 } 64 65 func Test_backOffDelay(t *testing.T) { 66 for i := 0; i < 10; i++ { 67 t.Log(BackOffDelay((i), time.Minute)) 68 } 69 }