forked from rbaliyan/event
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtesting.go
More file actions
374 lines (327 loc) · 9 KB
/
testing.go
File metadata and controls
374 lines (327 loc) · 9 KB
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
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
package event
import (
"context"
"fmt"
"sync"
"sync/atomic"
"time"
"github.com/rbaliyan/event/v3/transport"
"github.com/rbaliyan/event/v3/transport/message"
)
// testBusCounter ensures unique bus names across parallel tests.
var testBusCounter uint64
// TestBus creates a new bus configured for testing.
// The transport parameter is required - use channel.New() for in-memory testing.
// Has recovery/tracing/metrics disabled for simpler testing.
// Each call generates a unique bus name, safe for parallel tests.
// Returns an error if transport is nil or bus creation fails.
//
// Example:
//
// import "github.com/rbaliyan/event/v3/transport/channel"
// bus, err := event.TestBus(channel.New())
func TestBus(t transport.Transport) (*Bus, error) {
n := atomic.AddUint64(&testBusCounter, 1)
return NewBus(fmt.Sprintf("test-bus-%d", n),
WithTransport(t),
WithRecovery(false),
WithTracing(false),
WithMetrics(false),
)
}
// RecordedMessage represents a message that was published during a test
type RecordedMessage struct {
EventName string
Message message.Message
Timestamp time.Time
}
// RecordingTransport wraps a transport and records all published messages.
// Useful for testing that events are published correctly.
type RecordingTransport struct {
transport.Transport
mu sync.Mutex
messages []RecordedMessage
}
// NewRecordingTransport creates a transport that records all published messages.
// It wraps the provided transport (which is required).
//
// Example:
//
// import "github.com/rbaliyan/event/v3/transport/channel"
// transport, err := event.NewRecordingTransport(channel.New())
func NewRecordingTransport(t transport.Transport) (*RecordingTransport, error) {
if t == nil {
return nil, fmt.Errorf("event: transport is required for NewRecordingTransport")
}
return &RecordingTransport{
Transport: t,
messages: make([]RecordedMessage, 0),
}, nil
}
// Publish records the message and delegates to the underlying transport
func (t *RecordingTransport) Publish(ctx context.Context, name string, msg message.Message) error {
t.mu.Lock()
t.messages = append(t.messages, RecordedMessage{
EventName: name,
Message: msg,
Timestamp: time.Now(),
})
t.mu.Unlock()
return t.Transport.Publish(ctx, name, msg)
}
// Messages returns a copy of all recorded messages
func (t *RecordingTransport) Messages() []RecordedMessage {
t.mu.Lock()
defer t.mu.Unlock()
result := make([]RecordedMessage, len(t.messages))
copy(result, t.messages)
return result
}
// MessagesFor returns recorded messages for a specific event
func (t *RecordingTransport) MessagesFor(eventName string) []RecordedMessage {
t.mu.Lock()
defer t.mu.Unlock()
var result []RecordedMessage
for _, m := range t.messages {
if m.EventName == eventName {
result = append(result, m)
}
}
return result
}
// Reset clears all recorded messages
func (t *RecordingTransport) Reset() {
t.mu.Lock()
t.messages = make([]RecordedMessage, 0)
t.mu.Unlock()
}
// Count returns the number of recorded messages
func (t *RecordingTransport) Count() int {
t.mu.Lock()
defer t.mu.Unlock()
return len(t.messages)
}
// CountFor returns the number of messages for a specific event
func (t *RecordingTransport) CountFor(eventName string) int {
t.mu.Lock()
defer t.mu.Unlock()
count := 0
for _, m := range t.messages {
if m.EventName == eventName {
count++
}
}
return count
}
// TestHandler is a helper for testing event handlers.
// It collects all events received by the handler for later assertions.
type TestHandler[T any] struct {
mu sync.Mutex
received []TestHandlerCall[T]
handler func(context.Context, Event[T], T) error
}
// TestHandlerCall represents a single call to the test handler
type TestHandlerCall[T any] struct {
Context context.Context
Event Event[T]
Data T
Time time.Time
}
// NewTestHandler creates a new test handler.
// If handler is nil, it will acknowledge all messages.
func NewTestHandler[T any](handler func(context.Context, Event[T], T) error) *TestHandler[T] {
th := &TestHandler[T]{
received: make([]TestHandlerCall[T], 0),
handler: handler,
}
return th
}
// Handler returns the handler function for use with Subscribe
func (h *TestHandler[T]) Handler() Handler[T] {
return func(ctx context.Context, ev Event[T], data T) error {
h.mu.Lock()
h.received = append(h.received, TestHandlerCall[T]{
Context: ctx,
Event: ev,
Data: data,
Time: time.Now(),
})
h.mu.Unlock()
if h.handler != nil {
return h.handler(ctx, ev, data)
}
return nil
}
}
// Received returns a copy of all received calls
func (h *TestHandler[T]) Received() []TestHandlerCall[T] {
h.mu.Lock()
defer h.mu.Unlock()
result := make([]TestHandlerCall[T], len(h.received))
copy(result, h.received)
return result
}
// Count returns the number of calls received
func (h *TestHandler[T]) Count() int {
h.mu.Lock()
defer h.mu.Unlock()
return len(h.received)
}
// Last returns the last received call, or nil if none
func (h *TestHandler[T]) Last() *TestHandlerCall[T] {
h.mu.Lock()
defer h.mu.Unlock()
if len(h.received) == 0 {
return nil
}
call := h.received[len(h.received)-1]
return &call
}
// Reset clears all received calls
func (h *TestHandler[T]) Reset() {
h.mu.Lock()
h.received = make([]TestHandlerCall[T], 0)
h.mu.Unlock()
}
// WaitFor waits until the handler has received at least n calls or timeout is reached.
// Returns true if the expected count was reached, false on timeout.
func (h *TestHandler[T]) WaitFor(n int, timeout time.Duration) bool {
deadline := time.Now().Add(timeout)
for {
if h.Count() >= n {
return true
}
if time.Now().After(deadline) {
return false
}
time.Sleep(10 * time.Millisecond)
}
}
// BlockingTransport is a transport that blocks publishes until manually released.
// Useful for testing timeout and concurrency scenarios.
type BlockingTransport struct {
transport.Transport
blockCh chan struct{}
blocked bool
mu sync.Mutex
}
// NewBlockingTransport creates a transport that blocks all publishes.
// The transport parameter is required. Call Release() to unblock.
//
// Example:
//
// import "github.com/rbaliyan/event/v3/transport/channel"
// transport, err := event.NewBlockingTransport(channel.New())
func NewBlockingTransport(t transport.Transport) (*BlockingTransport, error) {
if t == nil {
return nil, fmt.Errorf("event: transport is required for NewBlockingTransport")
}
return &BlockingTransport{
Transport: t,
blockCh: make(chan struct{}),
blocked: true,
}, nil
}
// Publish blocks until Release is called, then delegates to underlying transport
func (t *BlockingTransport) Publish(ctx context.Context, name string, msg message.Message) error {
t.mu.Lock()
blocked := t.blocked
ch := t.blockCh
t.mu.Unlock()
if blocked {
select {
case <-ctx.Done():
return ctx.Err()
case <-ch:
// Unblocked
}
}
return t.Transport.Publish(ctx, name, msg)
}
// Release unblocks all waiting publishes
func (t *BlockingTransport) Release() {
t.mu.Lock()
defer t.mu.Unlock()
if t.blocked {
close(t.blockCh)
t.blocked = false
}
}
// Block creates a new block (for reuse after Release)
func (t *BlockingTransport) Block() {
t.mu.Lock()
defer t.mu.Unlock()
if !t.blocked {
t.blockCh = make(chan struct{})
t.blocked = true
}
}
// IsBlocked returns whether publishes are currently blocked
func (t *BlockingTransport) IsBlocked() bool {
t.mu.Lock()
defer t.mu.Unlock()
return t.blocked
}
// FailingTransport is a transport that fails publishes with a configured error.
// Useful for testing error handling.
type FailingTransport struct {
transport.Transport
mu sync.Mutex
err error
failAll bool
failNext int
}
// NewFailingTransport creates a transport that can be configured to fail.
// The transport parameter is required.
//
// Example:
//
// import "github.com/rbaliyan/event/v3/transport/channel"
// transport, err := event.NewFailingTransport(channel.New())
func NewFailingTransport(t transport.Transport) (*FailingTransport, error) {
if t == nil {
return nil, fmt.Errorf("event: transport is required for NewFailingTransport")
}
return &FailingTransport{
Transport: t,
}, nil
}
// Publish fails if configured, otherwise delegates to underlying transport
func (t *FailingTransport) Publish(ctx context.Context, name string, msg message.Message) error {
t.mu.Lock()
shouldFail := t.failAll || t.failNext > 0
err := t.err
if t.failNext > 0 {
t.failNext--
}
t.mu.Unlock()
if shouldFail {
if err != nil {
return err
}
return transport.ErrPublishTimeout
}
return t.Transport.Publish(ctx, name, msg)
}
// FailAll makes all publishes fail with the given error
func (t *FailingTransport) FailAll(err error) {
t.mu.Lock()
defer t.mu.Unlock()
t.failAll = true
t.err = err
}
// FailNext makes the next n publishes fail with the given error
func (t *FailingTransport) FailNext(n int, err error) {
t.mu.Lock()
defer t.mu.Unlock()
t.failNext = n
t.err = err
}
// Reset clears all failure configuration
func (t *FailingTransport) Reset() {
t.mu.Lock()
defer t.mu.Unlock()
t.failAll = false
t.failNext = 0
t.err = nil
}