-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathretry_test.go
58 lines (52 loc) · 1.4 KB
/
retry_test.go
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
package gokit
import (
"context"
"errors"
"testing"
"time"
)
func TestRetry(t *testing.T) {
// Test case 1: Retry succeeds on first attempt
count := 3
wait := 100 * time.Millisecond
err := Retry(context.Background(), count, wait, func() error {
return nil
})
if err != nil {
t.Errorf("Retry failed unexpectedly, error: %v", err)
}
// Test case 2: Retry fails after specified attempts
count = 3
wait = 100 * time.Millisecond
expectedErr := errors.New("retry failed")
err = Retry(context.Background(), count, wait, func() error {
return expectedErr
})
if !errors.Is(err, expectedErr) {
t.Errorf("Retry did not return expected error, expected: %v, got: %v", expectedErr, err)
}
// Test case 3: Retry succeeds after multiple attempts
count = 3
wait = 100 * time.Millisecond
attempts := 0
err = Retry(context.Background(), count, wait, func() error {
attempts++
if attempts < count {
return errors.New("retry failed")
}
return nil
})
if err != nil {
t.Errorf("Retry failed unexpectedly, error: %v", err)
}
// Test case 4: Retry fails after context is cancelled
errCancel := errors.New("context cancelled")
ctx, cancel := context.WithCancelCause(context.Background())
cancel(errCancel)
err = Retry(ctx, count, wait, func() error {
return nil
})
if context.Cause(ctx) != errCancel {
t.Errorf("Retry did not return expected error, expected: %v, got: %v", errCancel, err)
}
}