-
Notifications
You must be signed in to change notification settings - Fork 46
/
try_test.go
101 lines (93 loc) · 1.99 KB
/
try_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
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
97
98
99
100
101
package try_test
import (
"errors"
"fmt"
"log"
"testing"
"github.com/cheekybits/is"
"github.com/matryer/try"
)
func TestTryExample(t *testing.T) {
try.MaxRetries = 20
SomeFunction := func() (string, error) {
return "", nil
}
var value string
err := try.Do(func(attempt int) (bool, error) {
var err error
value, err = SomeFunction()
return attempt < 5, err // try 5 times
})
if err != nil {
log.Fatalln("error:", err)
}
}
func TestTryExamplePanic(t *testing.T) {
SomeFunction := func() (string, error) {
panic("something went badly wrong")
}
var value string
err := try.Do(func(attempt int) (retry bool, err error) {
retry = attempt < 5 // try 5 times
defer func() {
if r := recover(); r != nil {
err = errors.New(fmt.Sprintf("panic: %v", r))
}
}()
value, err = SomeFunction()
return
})
if err != nil {
//log.Fatalln("error:", err)
}
}
func TestTryDoSuccessful(t *testing.T) {
is := is.New(t)
callCount := 0
err := try.Do(func(attempt int) (bool, error) {
callCount++
return attempt < 5, nil
})
is.NoErr(err)
is.Equal(callCount, 1)
}
func TestTryDoFailed(t *testing.T) {
is := is.New(t)
theErr := errors.New("something went wrong")
callCount := 0
err := try.Do(func(attempt int) (bool, error) {
callCount++
return attempt < 5, theErr
})
is.Equal(err, theErr)
is.Equal(callCount, 5)
}
func TestTryPanics(t *testing.T) {
is := is.New(t)
theErr := errors.New("something went wrong")
callCount := 0
err := try.Do(func(attempt int) (retry bool, err error) {
retry = attempt < 5
defer func() {
if r := recover(); r != nil {
err = errors.New(fmt.Sprintf("panic: %v", r))
}
}()
callCount++
if attempt > 2 {
panic("I don't like three")
}
err = theErr
return
})
is.Equal(err.Error(), "panic: I don't like three")
is.Equal(callCount, 5)
}
func TestRetryLimit(t *testing.T) {
is := is.New(t)
err := try.Do(func(attempt int) (bool, error) {
return true, errors.New("nope")
})
is.OK(err)
is.Equal(try.IsMaxRetries(err), true)
}