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