...
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15 package retry
16
17 import (
18 "context"
19 "fmt"
20 "net/http"
21 "net/url"
22 "testing"
23 )
24
25 type temp struct{}
26
27 func (e temp) Error() string {
28 return "temporary error"
29 }
30
31 func (e temp) Temporary() bool {
32 return true
33 }
34
35 func TestRetry(t *testing.T) {
36 for i, test := range []struct {
37 predicate Predicate
38 err error
39 shouldRetry bool
40 }{{
41 predicate: IsTemporary,
42 err: nil,
43 shouldRetry: false,
44 }, {
45 predicate: IsTemporary,
46 err: fmt.Errorf("not temporary"),
47 shouldRetry: false,
48 }, {
49 predicate: IsNotNil,
50 err: fmt.Errorf("not temporary"),
51 shouldRetry: true,
52 }, {
53 predicate: IsTemporary,
54 err: temp{},
55 shouldRetry: true,
56 }, {
57 predicate: IsTemporary,
58 err: context.DeadlineExceeded,
59 shouldRetry: false,
60 }, {
61 predicate: IsTemporary,
62 err: &url.Error{
63 Op: http.MethodPost,
64 URL: "http://127.0.0.1:56520/v2/example/blobs/uploads/",
65 Err: context.DeadlineExceeded,
66 },
67 shouldRetry: false,
68 }} {
69
70 steps := 5
71 backoff := Backoff{
72 Steps: steps,
73 }
74
75
76 count := 0
77 f := func() error {
78 count++
79 return test.err
80 }
81
82 Retry(f, test.predicate, backoff)
83
84 if test.shouldRetry && count != steps {
85 t.Errorf("expected %d to retry %v, did not", i, test.err)
86 } else if !test.shouldRetry && count == steps {
87 t.Errorf("expected %d not to retry %v, but did", i, test.err)
88 }
89 }
90 }
91
92
93 func TestNil(t *testing.T) {
94 if err := Retry(nil, nil, Backoff{}); err == nil {
95 t.Errorf("got nil when passing in nil f")
96 }
97 if err := Retry(func() error { return nil }, nil, Backoff{}); err == nil {
98 t.Errorf("got nil when passing in nil p")
99 }
100 }
101
View as plain text