github.com/qiniu/go-sdk/v7@v7.27.0/storagev2/backoff/backoff_test.go (about) 1 //go:build unit 2 // +build unit 3 4 package backoff_test 5 6 import ( 7 "context" 8 "testing" 9 10 "github.com/alex-ant/gomath/rational" 11 "github.com/qiniu/go-sdk/v7/storagev2/backoff" 12 ) 13 14 func TestFixedBackoff(t *testing.T) { 15 b := backoff.NewFixedBackoff(100) 16 for i := 0; i < 1000; i++ { 17 if b.Time(context.Background(), nil) != 100 { 18 t.Fatal("unexpected") 19 } 20 } 21 } 22 23 func TestRandomizedBackoff(t *testing.T) { 24 b := backoff.NewRandomizedBackoff(backoff.NewFixedBackoff(100), rational.New(1, 2), rational.New(3, 2)) 25 for i := 0; i < 1000; i++ { 26 if wait := b.Time(context.Background(), nil); wait < 50 || wait > 150 { 27 t.Fatal("unexpected") 28 } 29 } 30 } 31 32 func TestLimitedBackoff(t *testing.T) { 33 b := backoff.NewLimitedBackoff(backoff.NewRandomizedBackoff(backoff.NewFixedBackoff(100), rational.New(1, 2), rational.New(3, 2)), 80, 120) 34 for i := 0; i < 1000; i++ { 35 if wait := b.Time(context.Background(), nil); wait < 80 || wait > 120 { 36 t.Fatal("unexpected") 37 } 38 } 39 } 40 41 func TestExponentialBackoff(t *testing.T) { 42 b := backoff.NewExponentialBackoff(100, 2) 43 if b.Time(context.Background(), &backoff.BackoffOptions{Attempts: 0}) != 100 { 44 t.Fatal("unexpected") 45 } 46 if b.Time(context.Background(), &backoff.BackoffOptions{Attempts: 1}) != 200 { 47 t.Fatal("unexpected") 48 } 49 if b.Time(context.Background(), &backoff.BackoffOptions{Attempts: 2}) != 400 { 50 t.Fatal("unexpected") 51 } 52 if b.Time(context.Background(), &backoff.BackoffOptions{Attempts: 3}) != 800 { 53 t.Fatal("unexpected") 54 } 55 if b.Time(context.Background(), &backoff.BackoffOptions{Attempts: 4}) != 1600 { 56 t.Fatal("unexpected") 57 } 58 }