-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathmock.go
662 lines (591 loc) · 14.5 KB
/
mock.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
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
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
package quartz
import (
"context"
"errors"
"fmt"
"slices"
"sync"
"testing"
"time"
)
// Mock is the testing implementation of Clock. It tracks a time that monotonically increases
// during a test, triggering any timers or tickers automatically.
type Mock struct {
tb testing.TB
mu sync.Mutex
// cur is the current time
cur time.Time
all []event
nextTime time.Time
nextEvents []event
traps []*Trap
}
type event interface {
next() time.Time
fire(t time.Time)
}
func (m *Mock) TickerFunc(ctx context.Context, d time.Duration, f func() error, tags ...string) Waiter {
if d <= 0 {
panic("TickerFunc called with negative or zero duration")
}
m.mu.Lock()
defer m.mu.Unlock()
c := newCall(clockFunctionTickerFunc, tags, withDuration(d))
m.matchCallLocked(c)
defer close(c.complete)
t := &mockTickerFunc{
ctx: ctx,
d: d,
f: f,
nxt: m.cur.Add(d),
mock: m,
cond: sync.NewCond(&m.mu),
}
m.all = append(m.all, t)
m.recomputeNextLocked()
go t.waitForCtx()
return t
}
func (m *Mock) NewTicker(d time.Duration, tags ...string) *Ticker {
if d <= 0 {
panic("NewTicker called with negative or zero duration")
}
m.mu.Lock()
defer m.mu.Unlock()
c := newCall(clockFunctionNewTicker, tags, withDuration(d))
m.matchCallLocked(c)
defer close(c.complete)
// 1 element buffer follows standard library implementation
ticks := make(chan time.Time, 1)
t := &Ticker{
C: ticks,
c: ticks,
d: d,
nxt: m.cur.Add(d),
mock: m,
}
m.addEventLocked(t)
return t
}
func (m *Mock) NewTimer(d time.Duration, tags ...string) *Timer {
m.mu.Lock()
defer m.mu.Unlock()
c := newCall(clockFunctionNewTimer, tags, withDuration(d))
defer close(c.complete)
m.matchCallLocked(c)
ch := make(chan time.Time, 1)
t := &Timer{
C: ch,
c: ch,
nxt: m.cur.Add(d),
mock: m,
}
if d <= 0 {
// zero or negative duration timer means we should immediately fire
// it, rather than add it.
go t.fire(t.mock.cur)
return t
}
m.addEventLocked(t)
return t
}
func (m *Mock) AfterFunc(d time.Duration, f func(), tags ...string) *Timer {
m.mu.Lock()
defer m.mu.Unlock()
c := newCall(clockFunctionAfterFunc, tags, withDuration(d))
defer close(c.complete)
m.matchCallLocked(c)
t := &Timer{
nxt: m.cur.Add(d),
fn: f,
mock: m,
}
if d <= 0 {
// zero or negative duration timer means we should immediately fire
// it, rather than add it.
go t.fire(t.mock.cur)
return t
}
m.addEventLocked(t)
return t
}
func (m *Mock) Now(tags ...string) time.Time {
m.mu.Lock()
defer m.mu.Unlock()
c := newCall(clockFunctionNow, tags)
defer close(c.complete)
m.matchCallLocked(c)
return m.cur
}
func (m *Mock) Since(t time.Time, tags ...string) time.Duration {
m.mu.Lock()
defer m.mu.Unlock()
c := newCall(clockFunctionSince, tags, withTime(t))
defer close(c.complete)
m.matchCallLocked(c)
return m.cur.Sub(t)
}
func (m *Mock) Until(t time.Time, tags ...string) time.Duration {
m.mu.Lock()
defer m.mu.Unlock()
c := newCall(clockFunctionUntil, tags, withTime(t))
defer close(c.complete)
m.matchCallLocked(c)
return t.Sub(m.cur)
}
func (m *Mock) addEventLocked(e event) {
m.all = append(m.all, e)
m.recomputeNextLocked()
}
func (m *Mock) recomputeNextLocked() {
var best time.Time
var events []event
for _, e := range m.all {
if best.IsZero() || e.next().Before(best) {
best = e.next()
events = []event{e}
continue
}
if e.next().Equal(best) {
events = append(events, e)
continue
}
}
m.nextTime = best
m.nextEvents = events
}
func (m *Mock) removeTimer(t *Timer) {
m.mu.Lock()
defer m.mu.Unlock()
m.removeTimerLocked(t)
}
func (m *Mock) removeTimerLocked(t *Timer) {
t.stopped = true
m.removeEventLocked(t)
}
func (m *Mock) removeEventLocked(e event) {
defer m.recomputeNextLocked()
for i := range m.all {
if m.all[i] == e {
m.all = append(m.all[:i], m.all[i+1:]...)
return
}
}
}
func (m *Mock) matchCallLocked(c *Call) {
var traps []*Trap
for _, t := range m.traps {
if t.matches(c) {
traps = append(traps, t)
}
}
if len(traps) == 0 {
return
}
c.releases.Add(len(traps))
m.mu.Unlock()
for _, t := range traps {
go t.catch(c)
}
c.releases.Wait()
m.mu.Lock()
}
// AdvanceWaiter is returned from Advance and Set calls and allows you to wait for ticks and timers
// to complete. In the case of functions passed to AfterFunc or TickerFunc, it waits for the
// functions to return. For other ticks & timers, it just waits for the tick to be delivered to
// the channel.
//
// If multiple timers or tickers trigger simultaneously, they are all run on separate
// go routines.
type AdvanceWaiter struct {
tb testing.TB
ch chan struct{}
}
// Wait for all timers and ticks to complete, or until context expires.
func (w AdvanceWaiter) Wait(ctx context.Context) error {
select {
case <-w.ch:
return nil
case <-ctx.Done():
return ctx.Err()
}
}
// MustWait waits for all timers and ticks to complete, and fails the test immediately if the
// context completes first. MustWait must be called from the goroutine running the test or
// benchmark, similar to `t.FailNow()`.
func (w AdvanceWaiter) MustWait(ctx context.Context) {
w.tb.Helper()
select {
case <-w.ch:
return
case <-ctx.Done():
w.tb.Fatalf("context expired while waiting for clock to advance: %s", ctx.Err())
}
}
// Done returns a channel that is closed when all timers and ticks complete.
func (w AdvanceWaiter) Done() <-chan struct{} {
return w.ch
}
// Advance moves the clock forward by d, triggering any timers or tickers. The returned value can
// be used to wait for all timers and ticks to complete. Advance sets the clock forward before
// returning, and can only advance up to the next timer or tick event. It will fail the test if you
// attempt to advance beyond.
//
// If you need to advance exactly to the next event, and don't know or don't wish to calculate it,
// consider AdvanceNext().
func (m *Mock) Advance(d time.Duration) AdvanceWaiter {
m.tb.Helper()
w := AdvanceWaiter{tb: m.tb, ch: make(chan struct{})}
m.mu.Lock()
fin := m.cur.Add(d)
// nextTime.IsZero implies no events scheduled.
if m.nextTime.IsZero() || fin.Before(m.nextTime) {
m.cur = fin
m.mu.Unlock()
close(w.ch)
return w
}
if fin.After(m.nextTime) {
m.tb.Errorf(fmt.Sprintf("cannot advance %s which is beyond next timer/ticker event in %s",
d.String(), m.nextTime.Sub(m.cur)))
m.mu.Unlock()
close(w.ch)
return w
}
m.cur = m.nextTime
go m.advanceLocked(w)
return w
}
func (m *Mock) advanceLocked(w AdvanceWaiter) {
defer close(w.ch)
wg := sync.WaitGroup{}
for i := range m.nextEvents {
e := m.nextEvents[i]
t := m.cur
wg.Add(1)
go func() {
e.fire(t)
wg.Done()
}()
}
// release the lock and let the events resolve. This allows them to call back into the
// Mock to query the time or set new timers. Each event should remove or reschedule
// itself from nextEvents.
m.mu.Unlock()
wg.Wait()
}
// Set the time to t. If the time is after the current mocked time, then this is equivalent to
// Advance() with the difference. You may only Set the time earlier than the current time before
// starting tickers and timers (e.g. at the start of your test case).
func (m *Mock) Set(t time.Time) AdvanceWaiter {
m.tb.Helper()
w := AdvanceWaiter{tb: m.tb, ch: make(chan struct{})}
m.mu.Lock()
if t.Before(m.cur) {
defer close(w.ch)
defer m.mu.Unlock()
// past
if !m.nextTime.IsZero() {
m.tb.Error("Set mock clock to the past after timers/tickers started")
}
m.cur = t
return w
}
// future
// nextTime.IsZero implies no events scheduled.
if m.nextTime.IsZero() || t.Before(m.nextTime) {
defer close(w.ch)
defer m.mu.Unlock()
m.cur = t
return w
}
if t.After(m.nextTime) {
defer close(w.ch)
defer m.mu.Unlock()
m.tb.Errorf("cannot Set time to %s which is beyond next timer/ticker event at %s",
t.String(), m.nextTime)
return w
}
m.cur = m.nextTime
go m.advanceLocked(w)
return w
}
// AdvanceNext advances the clock to the next timer or tick event. It fails the test if there are
// none scheduled. It returns the duration the clock was advanced and a waiter that can be used to
// wait for the timer/tick event(s) to finish.
func (m *Mock) AdvanceNext() (time.Duration, AdvanceWaiter) {
m.mu.Lock()
m.tb.Helper()
w := AdvanceWaiter{tb: m.tb, ch: make(chan struct{})}
if m.nextTime.IsZero() {
defer close(w.ch)
defer m.mu.Unlock()
m.tb.Error("cannot AdvanceNext because there are no timers or tickers running")
return 0, w
}
d := m.nextTime.Sub(m.cur)
m.cur = m.nextTime
go m.advanceLocked(w)
return d, w
}
// Peek returns the duration until the next ticker or timer event and the value
// true, or, if there are no running tickers or timers, it returns zero and
// false.
func (m *Mock) Peek() (d time.Duration, ok bool) {
m.mu.Lock()
defer m.mu.Unlock()
if m.nextTime.IsZero() {
return 0, false
}
return m.nextTime.Sub(m.cur), true
}
// Trapper allows the creation of Traps
type Trapper struct {
// mock is the underlying Mock. This is a thin wrapper around Mock so that
// we can have our interface look like mClock.Trap().NewTimer("foo")
mock *Mock
}
func (t Trapper) NewTimer(tags ...string) *Trap {
return t.mock.newTrap(clockFunctionNewTimer, tags)
}
func (t Trapper) AfterFunc(tags ...string) *Trap {
return t.mock.newTrap(clockFunctionAfterFunc, tags)
}
func (t Trapper) TimerStop(tags ...string) *Trap {
return t.mock.newTrap(clockFunctionTimerStop, tags)
}
func (t Trapper) TimerReset(tags ...string) *Trap {
return t.mock.newTrap(clockFunctionTimerReset, tags)
}
func (t Trapper) TickerFunc(tags ...string) *Trap {
return t.mock.newTrap(clockFunctionTickerFunc, tags)
}
func (t Trapper) TickerFuncWait(tags ...string) *Trap {
return t.mock.newTrap(clockFunctionTickerFuncWait, tags)
}
func (t Trapper) NewTicker(tags ...string) *Trap {
return t.mock.newTrap(clockFunctionNewTicker, tags)
}
func (t Trapper) TickerStop(tags ...string) *Trap {
return t.mock.newTrap(clockFunctionTickerStop, tags)
}
func (t Trapper) TickerReset(tags ...string) *Trap {
return t.mock.newTrap(clockFunctionTickerReset, tags)
}
func (t Trapper) Now(tags ...string) *Trap {
return t.mock.newTrap(clockFunctionNow, tags)
}
func (t Trapper) Since(tags ...string) *Trap {
return t.mock.newTrap(clockFunctionSince, tags)
}
func (t Trapper) Until(tags ...string) *Trap {
return t.mock.newTrap(clockFunctionUntil, tags)
}
func (m *Mock) Trap() Trapper {
return Trapper{m}
}
func (m *Mock) newTrap(fn clockFunction, tags []string) *Trap {
m.mu.Lock()
defer m.mu.Unlock()
tr := &Trap{
fn: fn,
tags: tags,
mock: m,
calls: make(chan *Call),
done: make(chan struct{}),
}
m.traps = append(m.traps, tr)
return tr
}
// NewMock creates a new Mock with the time set to midnight UTC on Jan 1, 2024.
// You may re-set the time earlier than this, but only before timers or tickers
// are created.
func NewMock(tb testing.TB) *Mock {
cur, err := time.Parse(time.RFC3339, "2024-01-01T00:00:00Z")
if err != nil {
panic(err)
}
return &Mock{
tb: tb,
cur: cur,
}
}
var _ Clock = &Mock{}
type mockTickerFunc struct {
ctx context.Context
d time.Duration
f func() error
nxt time.Time
mock *Mock
// cond is a condition Locked on the main Mock.mu
cond *sync.Cond
// inProgress is true when we are actively calling f
inProgress bool
// done is true when the ticker exits
done bool
// err holds the error when the ticker exits
err error
}
func (m *mockTickerFunc) next() time.Time {
return m.nxt
}
func (m *mockTickerFunc) fire(_ time.Time) {
m.mock.mu.Lock()
if m.done {
m.mock.mu.Unlock()
return
}
m.nxt = m.nxt.Add(m.d)
m.mock.recomputeNextLocked()
// we need this check to happen after we've computed the next tick,
// otherwise it will be immediately rescheduled.
if m.inProgress {
m.mock.mu.Unlock()
return
}
m.inProgress = true
m.mock.mu.Unlock()
err := m.f()
m.mock.mu.Lock()
defer m.mock.mu.Unlock()
m.inProgress = false
m.cond.Broadcast() // wake up anything waiting for f to finish
if err != nil {
m.exitLocked(err)
}
}
func (m *mockTickerFunc) exitLocked(err error) {
if m.done {
return
}
m.done = true
m.err = err
m.mock.removeEventLocked(m)
m.cond.Broadcast()
}
func (m *mockTickerFunc) waitForCtx() {
<-m.ctx.Done()
m.mock.mu.Lock()
defer m.mock.mu.Unlock()
for m.inProgress {
m.cond.Wait()
}
m.exitLocked(m.ctx.Err())
}
func (m *mockTickerFunc) Wait(tags ...string) error {
m.mock.mu.Lock()
defer m.mock.mu.Unlock()
c := newCall(clockFunctionTickerFuncWait, tags)
m.mock.matchCallLocked(c)
defer close(c.complete)
for !m.done {
m.cond.Wait()
}
return m.err
}
var _ Waiter = &mockTickerFunc{}
type clockFunction int
const (
clockFunctionNewTimer clockFunction = iota
clockFunctionAfterFunc
clockFunctionTimerStop
clockFunctionTimerReset
clockFunctionTickerFunc
clockFunctionTickerFuncWait
clockFunctionNewTicker
clockFunctionTickerReset
clockFunctionTickerStop
clockFunctionNow
clockFunctionSince
clockFunctionUntil
)
type callArg func(c *Call)
type Call struct {
Time time.Time
Duration time.Duration
Tags []string
fn clockFunction
releases sync.WaitGroup
complete chan struct{}
}
func (c *Call) Release() {
c.releases.Done()
<-c.complete
}
func withTime(t time.Time) callArg {
return func(c *Call) {
c.Time = t
}
}
func withDuration(d time.Duration) callArg {
return func(c *Call) {
c.Duration = d
}
}
func newCall(fn clockFunction, tags []string, args ...callArg) *Call {
c := &Call{
fn: fn,
Tags: tags,
complete: make(chan struct{}),
}
for _, a := range args {
a(c)
}
return c
}
type Trap struct {
fn clockFunction
tags []string
mock *Mock
calls chan *Call
done chan struct{}
}
func (t *Trap) catch(c *Call) {
select {
case t.calls <- c:
case <-t.done:
c.Release()
}
}
func (t *Trap) matches(c *Call) bool {
if t.fn != c.fn {
return false
}
for _, tag := range t.tags {
if !slices.Contains(c.Tags, tag) {
return false
}
}
return true
}
func (t *Trap) Close() {
t.mock.mu.Lock()
defer t.mock.mu.Unlock()
for i, tr := range t.mock.traps {
if t == tr {
t.mock.traps = append(t.mock.traps[:i], t.mock.traps[i+1:]...)
}
}
close(t.done)
}
var ErrTrapClosed = errors.New("trap closed")
func (t *Trap) Wait(ctx context.Context) (*Call, error) {
select {
case <-ctx.Done():
return nil, ctx.Err()
case <-t.done:
return nil, ErrTrapClosed
case c := <-t.calls:
return c, nil
}
}
// MustWait calls Wait() and then if there is an error, immediately fails the
// test via tb.Fatalf()
func (t *Trap) MustWait(ctx context.Context) *Call {
t.mock.tb.Helper()
c, err := t.Wait(ctx)
if err != nil {
t.mock.tb.Fatalf("context expired while waiting for trap: %s", err.Error())
}
return c
}