-
Notifications
You must be signed in to change notification settings - Fork 1
/
expectation.messagematch.go
334 lines (292 loc) · 8.54 KB
/
expectation.messagematch.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
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
package testkit
import (
"errors"
"fmt"
"reflect"
"github.com/dogmatiq/dogma"
"github.com/dogmatiq/enginekit/message"
"github.com/dogmatiq/testkit/envelope"
"github.com/dogmatiq/testkit/fact"
"github.com/dogmatiq/testkit/internal/inflect"
"github.com/dogmatiq/testkit/location"
)
// ToExecuteCommandMatching returns an expectation that passes if a command is
// executed that satisfies the given predicate function.
//
// Always prefer using [ToExecuteCommand] instead, if possible, as it provides
// more meaningful information in the result of a failure.
//
// pred is the predicate function. It is called for each executed command. It
// must return nil at least once for the expectation to pass.
//
// pred may return the [IgnoreMessage] error to indicate that the predicate does
// not apply to a specific message. Any command that is not of type T is also
// ignored.
func ToExecuteCommandMatching[T dogma.Command](
pred func(T) error,
) Expectation {
if pred == nil {
panic("ToExecuteCommandMatching(<nil>): function must not be nil")
}
return &messageMatchExpectation[T]{
pred: pred,
exhaustive: false,
}
}
// ToOnlyExecuteCommandsMatching returns an expectation that passes if all
// executed commands satisfy the given predicate function.
//
// The expectation does NOT fail if other unrelated actions are performed, such
// as recording an event.
//
// pred is the predicate function. It is called for each executed command. It
// must return nil (or [IgnoreMessage]) every time for the expectation to pass.
//
// pred may return the [IgnoreMessage] error to indicate that the predicate does
// not apply to a specific message.
//
// If any command is executed that is not of type T, the expectation fails.
func ToOnlyExecuteCommandsMatching[T dogma.Command](
pred func(T) error,
) Expectation {
if pred == nil {
panic("ToOnlyExecuteCommandsMatching(<nil>): function must not be nil")
}
return &messageMatchExpectation[T]{
pred: pred,
exhaustive: true,
}
}
// ToRecordEventMatching returns an expectation that passes if an event is
// recorded that satisfies the given predicate function.
//
// Always prefer using [ToRecordEvent] instead, if possible, as it provides more
// meaningful information in the result of a failure.
//
// pred is the predicate function. It is called for each recorded event. It must
// return nil at least once for the expectation to pass.
//
// pred may return the [IgnoreMessage] error to indicate that the predicate does
// not apply to a specific message. Any event that is not of type T is also
// ignored.
func ToRecordEventMatching[T dogma.Event](
pred func(T) error,
) Expectation {
if pred == nil {
panic("ToRecordEventMatching(<nil>): function must not be nil")
}
return &messageMatchExpectation[T]{
pred: pred,
exhaustive: false,
}
}
// ToOnlyRecordEventsMatching returns an expectation that passes if all
// recorded events satisfy the given predicate function.
//
// The expectation does NOT fail if other unrelated actions are performed, such
// as executing a command.
//
// pred is the predicate function. It is called for each recorded event. It
// must return nil (or [IgnoreMessage]) every time for the expectation to pass.
//
// pred may return the [IgnoreMessage] error to indicate that the predicate does
// not apply to a specific message.
//
// If any event is recorded that is not of type T, the expectation fails.
func ToOnlyRecordEventsMatching[T dogma.Event](
pred func(T) error,
) Expectation {
if pred == nil {
panic("ToOnlyRecordEventsMatching(<nil>): function must not be nil")
}
return &messageMatchExpectation[T]{
pred: pred,
exhaustive: true,
}
}
// IgnoreMessage is an error that can be returned by predicate functions to
// indicate that the predicate does not care about the message and therefore the
// predicate's result should not affect the expectation's result.
var IgnoreMessage = errors.New("this message does not need to be inspected by the predicate") //revive:disable-line:error-naming
// messageMatchExpectation is an Expectation that checks that at least one
// message that satisfies a predicate function is produced.
//
// It is the implementation used by [ToExecuteCommandMatching],
// [ToRecordEventMatching], [ToOnlyExecuteCommandsMatching], and
// [ToOnlyRecordEventsMatching].
type messageMatchExpectation[T dogma.Message] struct {
pred func(T) error
exhaustive bool
}
func (e *messageMatchExpectation[T]) Caption() string {
if e.exhaustive {
return inflect.Sprintf(
message.KindFor[T](),
"to only <produce> <messages> that match the predicate near %s",
location.OfFunc(e.pred),
)
}
return inflect.Sprintf(
message.KindFor[T](),
"to <produce> a <message> that matches the predicate near %s",
location.OfFunc(e.pred),
)
}
func (e *messageMatchExpectation[T]) Predicate(s PredicateScope) (Predicate, error) {
t := message.TypeFor[T]()
if t.ReflectType().Kind() != reflect.Interface {
if err := guardAgainstExpectationOnImpossibleType(s, t); err != nil {
return nil, err
}
}
return &messageMatchPredicate[T]{
pred: e.pred,
exhaustive: e.exhaustive,
tracker: tracker{
kind: message.KindFor[T](),
options: s.Options,
},
}, nil
}
// messageMatchPredicate is the [Predicate] implementation for
// [messageMatchExpectation].
type messageMatchPredicate[T dogma.Message] struct {
pred func(T) error
exhaustive bool
failures []*failedMatch
matched int
ignored int
ok bool
tracker tracker
}
// Notify updates the expectation's state in response to a new fact.
func (p *messageMatchPredicate[T]) Notify(f fact.Fact) {
if p.ok {
return
}
if env, ok := p.tracker.Notify(f); ok {
p.messageProduced(env)
}
}
// messageProduced updates the predicate's state to reflect the fact that a
// message of the expected kind has been produced.
func (p *messageMatchPredicate[T]) messageProduced(env *envelope.Envelope) {
expectedType := message.TypeFor[T]()
producedType := message.TypeOf(env.Message)
if producedType.Kind() != expectedType.Kind() {
return
}
var err error
if m, ok := env.Message.(T); ok {
err = p.pred(m)
} else if p.exhaustive {
err = fmt.Errorf("predicate function expected %s", expectedType)
} else {
err = IgnoreMessage
}
if err == nil {
p.matched++
if !p.exhaustive {
// We're only looking for "at least one match", and we've found it.
// Mark the predicate as satisfied so that we don't bother looking
// for future matches.
p.ok = true
p.failures = nil
}
return
}
if err == IgnoreMessage {
p.ignored++
return
}
for _, f := range p.failures {
if f.MessageType == producedType && f.Error == err.Error() {
f.Count++
return
}
}
p.failures = append(
p.failures,
&failedMatch{
MessageType: producedType,
Error: err.Error(),
Count: 1,
},
)
}
func (p *messageMatchPredicate[T]) Ok() bool {
return p.ok
}
func (p *messageMatchPredicate[T]) Done() {
if p.exhaustive && len(p.failures) == 0 {
p.ok = true
}
}
func (p *messageMatchPredicate[T]) Report(ctx ReportGenerationContext) *Report {
k := message.KindFor[T]()
rep := &Report{
TreeOk: ctx.TreeOk,
Ok: p.ok,
Criteria: inflect.Sprintf(
k,
"<produce> a <message> that matches the predicate near %s",
location.OfFunc(p.pred),
),
}
if p.exhaustive {
rep.Criteria = inflect.Sprintf(
k,
"only <produce> <messages> that match the predicate near %s",
location.OfFunc(p.pred),
)
}
if p.ok || ctx.TreeOk || ctx.IsInverted {
return rep
}
if len(p.failures) > 0 {
s := rep.Section(failedMatchesSection)
for _, f := range p.failures {
if f.Count > 1 {
s.AppendListItem(
"%s: %s (repeated %d times)",
f.MessageType,
f.Error,
f.Count,
)
} else {
s.AppendListItem(
"%s: %s",
f.MessageType,
f.Error,
)
}
}
}
suggestions := rep.Section(suggestionsSection)
if p.ignored > 0 {
suggestions.AppendListItem(
"verify the logic within the predicate function, it ignored %s",
inflect.Sprintf(k, "%d <messages>", p.ignored),
)
} else if len(p.failures) > 0 {
suggestions.AppendListItem("verify the logic within the predicate function")
}
reportNoMatch(rep, &p.tracker)
if p.exhaustive {
matched := fmt.Sprintf("only %d of %d", p.matched, p.tracker.produced-p.ignored)
if p.matched == 0 {
matched = fmt.Sprintf("none of the %d", p.tracker.produced-p.ignored)
}
rep.Explanation = inflect.Sprintf(
k,
"%s relevant <messages> matched the predicate",
matched,
)
}
return rep
}
type failedMatch struct {
MessageType message.Type
Error string
Count int
}