forked from jdvr/go-again
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmock_operation_test.go
80 lines (72 loc) · 2 KB
/
mock_operation_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
package again_test
import (
"context"
"errors"
"github.com/stretchr/testify/require"
"testing"
)
type inputCall struct {
ctx context.Context
fakeOperation *FakeOperation
}
func (currentCall inputCall) Returns(value int, err error) *FakeOperation {
expectedCalls := currentCall.fakeOperation.expectedCalls[currentCall.ctx]
expectedCalls = append(expectedCalls, call{
input: currentCall.ctx,
value: value,
err: err,
})
currentCall.fakeOperation.expectedCalls[currentCall.ctx] = expectedCalls
return currentCall.fakeOperation
}
type call struct {
input context.Context
value int
err error
}
type FakeOperation struct {
t *testing.T
times int
called []call
expectedCalls map[context.Context][]call
allowAnyCall bool
}
func NewFakeOperation(t *testing.T) *FakeOperation {
t.Helper()
return &FakeOperation{
t: t,
expectedCalls: make(map[context.Context][]call),
}
}
func (currentFakeOperator *FakeOperation) Run(context context.Context) (int, error) {
expectedCalls, ok := currentFakeOperator.expectedCalls[context]
require.True(
currentFakeOperator.t,
ok || currentFakeOperator.allowAnyCall,
"Unexpected call for FakeOperation",
)
expectedCall := call{
input: context,
value: 23,
err: errors.New("default err"),
}
if !currentFakeOperator.allowAnyCall {
require.NotZero(currentFakeOperator.t, expectedCalls)
call := expectedCalls[0]
expectedCall = call
currentFakeOperator.expectedCalls[context] = expectedCalls[1:]
}
currentFakeOperator.called = append(currentFakeOperator.called, expectedCall)
currentFakeOperator.times += 1
return expectedCall.value, expectedCall.err
}
func (currentFakeOperator *FakeOperation) givenContext(ctx context.Context) inputCall {
require.NotNil(currentFakeOperator.t, ctx)
return inputCall{
ctx: ctx,
fakeOperation: currentFakeOperator,
}
}
func (currentFakeOperator FakeOperation) haveBeenCalled(times int) {
require.Equal(currentFakeOperator.t, times, currentFakeOperator.times)
}