github.com/vnforks/kid/v5@v5.22.1-0.20200408055009-b89d99c65676/utils/backoff_test.go (about)

     1  // Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
     2  // See LICENSE.txt for license information.
     3  
     4  package utils
     5  
     6  import (
     7  	"testing"
     8  
     9  	"github.com/pkg/errors"
    10  	"github.com/stretchr/testify/assert"
    11  	"github.com/stretchr/testify/require"
    12  )
    13  
    14  func TestProgressiveRetry(t *testing.T) {
    15  	var retries int
    16  
    17  	type args struct {
    18  		operation func() error
    19  	}
    20  	tests := []struct {
    21  		name            string
    22  		args            args
    23  		wantErr         bool
    24  		expectedRetries int
    25  	}{
    26  		{
    27  			name: "Should fail and return error",
    28  			args: args{
    29  				operation: func() error {
    30  					retries++
    31  					return errors.New("Operation Failed")
    32  				},
    33  			},
    34  			wantErr:         true,
    35  			expectedRetries: 6,
    36  		},
    37  		{
    38  			name: "Should succeed after two retries",
    39  			args: args{
    40  				operation: func() error {
    41  					retries++
    42  					if retries == 2 {
    43  						return nil
    44  					}
    45  
    46  					return errors.New("Operation Failed")
    47  				},
    48  			},
    49  			wantErr:         false,
    50  			expectedRetries: 2,
    51  		},
    52  	}
    53  	for _, tt := range tests {
    54  		t.Run(tt.name, func(t *testing.T) {
    55  			retries = 0
    56  
    57  			err := ProgressiveRetry(tt.args.operation)
    58  			if !tt.wantErr {
    59  				require.Nil(t, err)
    60  			}
    61  
    62  			assert.Equal(t, tt.expectedRetries, retries)
    63  		})
    64  	}
    65  }