/
executor_test.go
75 lines (63 loc) · 2.07 KB
/
executor_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
package failsafe_test
import (
"context"
"testing"
"github.com/stretchr/testify/assert"
"github.com/failsafe-go/failsafe-go"
"github.com/failsafe-go/failsafe-go/fallback"
"github.com/failsafe-go/failsafe-go/internal/testutil"
"github.com/failsafe-go/failsafe-go/retrypolicy"
)
func TestRunWithSuccess(t *testing.T) {
rp := retrypolicy.WithDefaults[any]()
err := failsafe.Run(func() error {
return nil
}, rp)
assert.Nil(t, err)
}
func TestGetWithSuccess(t *testing.T) {
rp := retrypolicy.WithDefaults[string]()
result, err := failsafe.Get(func() (string, error) {
return "test", nil
}, rp)
assert.Equal(t, "test", result)
assert.Nil(t, err)
}
func TestGetWithFailure(t *testing.T) {
rp := retrypolicy.WithDefaults[string]()
result, err := failsafe.Get(func() (string, error) {
return "", testutil.ErrInvalidArgument
}, rp)
assert.Empty(t, result)
assert.ErrorIs(t, err, testutil.ErrInvalidArgument)
}
func TestGetWithExecution(t *testing.T) {
rp := retrypolicy.WithDefaults[string]()
fb := fallback.WithResult("fallback")
var lasteExec failsafe.Execution[string]
result, err := failsafe.GetWithExecution(func(exec failsafe.Execution[string]) (string, error) {
lasteExec = exec
return "", testutil.ErrInvalidArgument
}, fb, rp)
assert.Equal(t, "fallback", result)
assert.Nil(t, err)
assert.Equal(t, 3, lasteExec.Attempts())
assert.Equal(t, 3, lasteExec.Executions())
assert.Equal(t, "", lasteExec.LastResult())
assert.Equal(t, testutil.ErrInvalidArgument, lasteExec.LastError())
}
// Asserts that configuring a context returns a new copy of the Executor.
func TestWithContext(t *testing.T) {
ctx1 := context.Background()
ctx2 := context.Background()
executor1 := failsafe.NewExecutor[any](retrypolicy.WithDefaults[any]()).WithContext(ctx1)
executor2 := executor1.WithContext(ctx2)
assert.NotSame(t, executor1, executor2)
}
func TestExecutionWithNoPolicies(t *testing.T) {
result, err := failsafe.Get(func() (string, error) {
return "test", testutil.ErrInvalidArgument
})
assert.Equal(t, "test", result)
assert.ErrorIs(t, testutil.ErrInvalidArgument, err)
}