/
callrecord.go
235 lines (210 loc) · 5.99 KB
/
callrecord.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
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
// Package ut implements some testing utilities. So far it includes CallTracker, which helps you build
// mock implementations of interfaces.
package ut
import (
"bytes"
"fmt"
"reflect"
"runtime"
"sync"
"testing"
)
// CallTracker is an interface to help build mocks.
//
// Build the CallTracker interface into your mocks. Use TrackCall within mock methods to track calls to the method
// and the parameters used.
// Within tests use AddCall to add expected method calls, and SetReturns to indicate what the calls will return.
//
// The tests for this package contain a full example.
//
// type MyMock struct {ut.CallTracker}
//
// func (m *MyMock) AFunction(p int) error {
// r := m.TrackCall("AFunction", p)
// return NilOrError(r[0])
// }
//
// func Something(m Functioner) {
// m.AFunction(37)
// }
//
// func TestSomething(t *testing.T) {
// m := &MyMock{NewCallRecords(t)}
// m.AddCall("AFunction", 37).SetReturns(nil)
//
// Something(m)
//
// m.AssertDone()
// }
type CallTracker interface {
// AddCall() is used by tests to add an expected call to the tracker
AddCall(name string, params ...any) CallTracker
// SetReturns() is called immediately after AddCall() to set the return
// values for the call.
SetReturns(returns ...any) CallTracker
// TrackCall() is called within mocks to track a call to the Mock. It
// returns the return values registered via SetReturns()
TrackCall(name string, params ...any) []any
// AssertDone() should be called at the end of a test to confirm all
// the expected calls have been made
AssertDone()
// RecordCall() is called to indicate calls to the named mock method should
// be recorded rather than asserted. The parameters to any call to the
// named method will be recorded and may be retrieved via GetRecordedParams.
// The returns from the method are also specified on this call and must be
// the same each time.
// Note that the ordering of recorded calls relative to other calls is not
// tracked.
RecordCall(name string, returns ...any) CallTracker
// GetRecordedParams returns the sets of parameters passed to a call captured
// via RecordCall
GetRecordedParams(name string) ([][]any, bool)
}
type callRecord struct {
name string
params []any
returns []any
}
func (e *callRecord) assert(t testing.TB, name string, params ...any) {
if name != e.name {
t.Logf("Expected call to %s%s", e.name, paramsToString(e.params))
t.Logf(" got call to %s%s", name, paramsToString(params))
showStack(t)
t.Fail()
return
}
if len(params) != len(e.params) {
t.Logf("Call to (%s) unexpected parameters", name)
t.Logf(" expected %s", paramsToString(e.params))
t.Logf(" got %s", paramsToString(params))
showStack(t)
t.FailNow()
return
}
for i, ap := range params {
ep := e.params[i]
if ap == nil && ep == nil {
continue
}
switch ep := ep.(type) {
case func(actual any):
ep(ap)
default:
if !reflect.DeepEqual(ap, ep) {
t.Logf("Call to %s parameter %d unexpected", name, i)
t.Logf(" expected %#v (%T)", ep, ep)
t.Logf(" got %#v (%T)", ap, ap)
showStack(t)
t.Fail()
}
}
}
}
func showStack(t testing.TB) {
pc := make([]uintptr, 10)
n := runtime.Callers(4, pc)
for i := 0; i < n; i++ {
f := runtime.FuncForPC(pc[i])
file, line := f.FileLine(pc[i])
t.Logf(" %s (%s line %d", f.Name(), file, line)
}
}
func paramsToString(params []any) string {
w := &bytes.Buffer{}
w.WriteString("(")
l := len(params)
for i, p := range params {
fmt.Fprintf(w, "%#v", p)
if i < l-1 {
w.WriteString(", ")
}
}
w.WriteString(")")
return w.String()
}
// recording tracks calls actually made to the mock. It is used only when the
// user choses to record calls for a method rather than assert them
type recording struct {
// The returned values are the same for each call to a recorded method.
returns []any
// We record the parameters from each call to the method.
params [][]any
}
type callRecords struct {
sync.Mutex
t testing.TB
calls []callRecord
records map[string]*recording
current int
}
// NewCallRecords creates a new call tracker
func NewCallRecords(t testing.TB) CallTracker {
return &callRecords{
t: t,
records: make(map[string]*recording),
}
}
func (cr *callRecords) AddCall(name string, params ...any) CallTracker {
cr.calls = append(cr.calls, callRecord{name: name, params: params})
return cr
}
func (cr *callRecords) RecordCall(name string, returns ...any) CallTracker {
cr.records[name] = &recording{
returns: returns,
params: make([][]any, 0),
}
return cr
}
func (cr *callRecords) SetReturns(returns ...any) CallTracker {
cr.calls[len(cr.calls)-1].returns = returns
return cr
}
func (cr *callRecords) TrackCall(name string, params ...any) []any {
cr.Lock()
defer cr.Unlock()
if record, ok := cr.records[name]; ok {
// Call is to be recorded, not asserted
record.params = append(record.params, params)
return record.returns
}
// Call is to be asserted
if cr.current >= len(cr.calls) {
cr.t.Logf("Unexpected call to %s%s", name, paramsToString(params))
showStack(cr.t)
cr.t.FailNow()
}
expectedCall := cr.calls[cr.current]
expectedCall.assert(cr.t, name, params...)
cr.current += 1
return expectedCall.returns
}
func (cr *callRecords) AssertDone() {
if cr.current < len(cr.calls) {
// We don't call Fatalf or FailNow because that may mask other errors if this AssertDone
// is called from a defer
missed := &bytes.Buffer{}
for i, call := range cr.calls[cr.current:] {
if i != 0 {
missed.WriteString(", ")
}
missed.WriteString(call.name)
}
cr.t.Errorf("Only %d of %d expected calls made. Missed calls to %s", cr.current, len(cr.calls), missed)
}
}
func (cr *callRecords) GetRecordedParams(name string) ([][]any, bool) {
cr.Lock()
defer cr.Unlock()
record, ok := cr.records[name]
if ok {
return record.params, true
}
return nil, false
}
// NilOrError is a utility function for returning err from mocked methods
func NilOrError(val any) error {
if val == nil {
return nil
}
return val.(error)
}