github.com/msales/pkg/v3@v3.24.0/retry/retry_test.go (about)

     1  package retry_test
     2  
     3  import (
     4  	"errors"
     5  	"testing"
     6  	"time"
     7  
     8  	"github.com/msales/pkg/v3/retry"
     9  	"github.com/stretchr/testify/assert"
    10  )
    11  
    12  func TestExponentialPolicy(t *testing.T) {
    13  	p := retry.ExponentialPolicy(3, time.Millisecond)
    14  
    15  	sleep, ok := p.Next()
    16  	assert.True(t, ok)
    17  	assert.Equal(t, time.Millisecond, sleep)
    18  
    19  	sleep, ok = p.Next()
    20  	assert.True(t, ok)
    21  	assert.Equal(t, 2*time.Millisecond, sleep)
    22  
    23  	sleep, ok = p.Next()
    24  	assert.False(t, ok)
    25  	assert.Zero(t, sleep)
    26  
    27  	sleep, ok = p.Next()
    28  	assert.False(t, ok)
    29  	assert.Zero(t, sleep)
    30  }
    31  
    32  func TestRun(t *testing.T) {
    33  	var i int
    34  	retry.Run(retry.ExponentialPolicy(3, time.Nanosecond), func() error {
    35  		i++
    36  		return nil
    37  	})
    38  
    39  	assert.Equal(t, 1, i)
    40  }
    41  
    42  func TestRun_NilPolicy(t *testing.T) {
    43  	err := retry.Run(nil, func() error {
    44  		return nil
    45  	})
    46  	assert.Error(t, err)
    47  }
    48  
    49  func TestRun_MaxAttempts(t *testing.T) {
    50  	var i int
    51  	retry.Run(retry.ExponentialPolicy(3, time.Nanosecond), func() error {
    52  		i++
    53  		return errors.New("test error")
    54  	})
    55  
    56  	assert.Equal(t, 3, i)
    57  }
    58  
    59  func TestStop(t *testing.T) {
    60  	var i int
    61  	retry.Run(retry.ExponentialPolicy(3, time.Nanosecond), func() error {
    62  		i++
    63  		return retry.Stop(errors.New("test error"))
    64  	})
    65  
    66  	assert.Equal(t, 1, i)
    67  }