github.com/xtls/xray-core@v1.8.12-0.20240518155711-3168d27b0bdb/common/retry/retry_test.go (about)

     1  package retry_test
     2  
     3  import (
     4  	"testing"
     5  	"time"
     6  
     7  	"github.com/xtls/xray-core/common"
     8  	"github.com/xtls/xray-core/common/errors"
     9  	. "github.com/xtls/xray-core/common/retry"
    10  )
    11  
    12  var errorTestOnly = errors.New("this is a fake error")
    13  
    14  func TestNoRetry(t *testing.T) {
    15  	startTime := time.Now().Unix()
    16  	err := Timed(10, 100000).On(func() error {
    17  		return nil
    18  	})
    19  	endTime := time.Now().Unix()
    20  
    21  	common.Must(err)
    22  	if endTime < startTime {
    23  		t.Error("endTime < startTime: ", startTime, " -> ", endTime)
    24  	}
    25  }
    26  
    27  func TestRetryOnce(t *testing.T) {
    28  	startTime := time.Now()
    29  	called := 0
    30  	err := Timed(10, 1000).On(func() error {
    31  		if called == 0 {
    32  			called++
    33  			return errorTestOnly
    34  		}
    35  		return nil
    36  	})
    37  	duration := time.Since(startTime)
    38  
    39  	common.Must(err)
    40  	if v := int64(duration / time.Millisecond); v < 900 {
    41  		t.Error("duration: ", v)
    42  	}
    43  }
    44  
    45  func TestRetryMultiple(t *testing.T) {
    46  	startTime := time.Now()
    47  	called := 0
    48  	err := Timed(10, 1000).On(func() error {
    49  		if called < 5 {
    50  			called++
    51  			return errorTestOnly
    52  		}
    53  		return nil
    54  	})
    55  	duration := time.Since(startTime)
    56  
    57  	common.Must(err)
    58  	if v := int64(duration / time.Millisecond); v < 4900 {
    59  		t.Error("duration: ", v)
    60  	}
    61  }
    62  
    63  func TestRetryExhausted(t *testing.T) {
    64  	startTime := time.Now()
    65  	called := 0
    66  	err := Timed(2, 1000).On(func() error {
    67  		called++
    68  		return errorTestOnly
    69  	})
    70  	duration := time.Since(startTime)
    71  
    72  	if errors.Cause(err) != ErrRetryFailed {
    73  		t.Error("cause: ", err)
    74  	}
    75  
    76  	if v := int64(duration / time.Millisecond); v < 1900 {
    77  		t.Error("duration: ", v)
    78  	}
    79  }
    80  
    81  func TestExponentialBackoff(t *testing.T) {
    82  	startTime := time.Now()
    83  	called := 0
    84  	err := ExponentialBackoff(10, 100).On(func() error {
    85  		called++
    86  		return errorTestOnly
    87  	})
    88  	duration := time.Since(startTime)
    89  
    90  	if errors.Cause(err) != ErrRetryFailed {
    91  		t.Error("cause: ", err)
    92  	}
    93  	if v := int64(duration / time.Millisecond); v < 4000 {
    94  		t.Error("duration: ", v)
    95  	}
    96  }