github.com/hashicorp/vault/sdk@v0.11.0/helper/backoff/backoff_test.go (about)

     1  // Copyright (c) HashiCorp, Inc.
     2  // SPDX-License-Identifier: MPL-2.0
     3  
     4  package backoff
     5  
     6  import (
     7  	"testing"
     8  	"time"
     9  
    10  	"github.com/stretchr/testify/assert"
    11  )
    12  
    13  // TestBackoff_Basic tests that basic exponential backoff works as expected up to a max of 3 times.
    14  func TestBackoff_Basic(t *testing.T) {
    15  	for i := 0; i < 100; i++ {
    16  		b := NewBackoff(3, 1*time.Millisecond, 10*time.Millisecond)
    17  		x, err := b.Next()
    18  		assert.Nil(t, err)
    19  		assert.LessOrEqual(t, x, 1*time.Millisecond)
    20  		assert.GreaterOrEqual(t, x, 750*time.Microsecond)
    21  
    22  		x2, err := b.Next()
    23  		assert.Nil(t, err)
    24  		assert.LessOrEqual(t, x2, x*2)
    25  		assert.GreaterOrEqual(t, x2, x*3/4)
    26  
    27  		x3, err := b.Next()
    28  		assert.Nil(t, err)
    29  		assert.LessOrEqual(t, x3, x2*2)
    30  		assert.GreaterOrEqual(t, x3, x2*3/4)
    31  
    32  		_, err = b.Next()
    33  		assert.NotNil(t, err)
    34  	}
    35  }
    36  
    37  // TestBackoff_ZeroRetriesAlwaysFails checks that if retries is set to zero, then an error is returned immediately.
    38  func TestBackoff_ZeroRetriesAlwaysFails(t *testing.T) {
    39  	b := NewBackoff(0, 1*time.Millisecond, 10*time.Millisecond)
    40  	_, err := b.Next()
    41  	assert.NotNil(t, err)
    42  }
    43  
    44  // TestBackoff_MaxIsEnforced checks that the maximum backoff is enforced.
    45  func TestBackoff_MaxIsEnforced(t *testing.T) {
    46  	b := NewBackoff(1001, 1*time.Millisecond, 2*time.Millisecond)
    47  	for i := 0; i < 1000; i++ {
    48  		x, err := b.Next()
    49  		assert.LessOrEqual(t, x, 2*time.Millisecond)
    50  		assert.Nil(t, err)
    51  	}
    52  }