mirror of
https://github.com/coder/coder.git
synced 2026-11-15 03:20:13 +08:00
Adds a package for testing time/timer/ticker functions. Implementation is limited to `NewTimer` and `NewContextTicker`, but will eventually be expanded to all `time` functions from the standard library as well as `context.WithTimeout()`, `context.WithDeadline()`. Replaces `benbjohnson/clock` for the pubsub watchdog, as a proof of concept. Eventually, as we expand functionality, we will replace most time-related functions with this library for testing.
59 lines
915 B
Go
59 lines
915 B
Go
package clock
|
|
|
|
import (
|
|
"context"
|
|
"time"
|
|
)
|
|
|
|
type realClock struct{}
|
|
|
|
func NewReal() Clock {
|
|
return realClock{}
|
|
}
|
|
|
|
func (realClock) TickerFunc(ctx context.Context, d time.Duration, f func() error, _ ...string) Waiter {
|
|
ct := &realContextTicker{
|
|
ctx: ctx,
|
|
tkr: time.NewTicker(d),
|
|
f: f,
|
|
err: make(chan error, 1),
|
|
}
|
|
go ct.run()
|
|
return ct
|
|
}
|
|
|
|
type realContextTicker struct {
|
|
ctx context.Context
|
|
tkr *time.Ticker
|
|
f func() error
|
|
err chan error
|
|
}
|
|
|
|
func (t *realContextTicker) Wait(_ ...string) error {
|
|
return <-t.err
|
|
}
|
|
|
|
func (t *realContextTicker) run() {
|
|
defer t.tkr.Stop()
|
|
for {
|
|
select {
|
|
case <-t.ctx.Done():
|
|
t.err <- t.ctx.Err()
|
|
return
|
|
case <-t.tkr.C:
|
|
err := t.f()
|
|
if err != nil {
|
|
t.err <- err
|
|
return
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
func (realClock) NewTimer(d time.Duration, _ ...string) *Timer {
|
|
rt := time.NewTimer(d)
|
|
return &Timer{C: rt.C, timer: rt}
|
|
}
|
|
|
|
var _ Clock = realClock{}
|