package dregarnuhr import ( "sync" "testing" "time" ) type fakeClock struct { mu sync.Mutex now time.Time timers map[*fakeTimer]time.Time created chan struct{} } type fakeTimer struct { clock *fakeClock ch chan time.Time } func newFakeClock() *fakeClock { return &fakeClock{now: time.Unix(100000, 0), timers: map[*fakeTimer]time.Time{}, created: make(chan struct{}, 100)} } func (c *fakeClock) Now() time.Time { c.mu.Lock(); defer c.mu.Unlock(); return c.now } func (c *fakeClock) NewTimer(delay time.Duration) Timer { c.mu.Lock() defer c.mu.Unlock() t := &fakeTimer{clock: c, ch: make(chan time.Time, 1)} if delay <= 0 { t.ch <- c.now } else { c.timers[t] = c.now.Add(delay) } c.created <- struct{}{} return t } func (t *fakeTimer) C() <-chan time.Time { return t.ch } func (t *fakeTimer) Stop() bool { t.clock.mu.Lock() defer t.clock.mu.Unlock() _, ok := t.clock.timers[t] delete(t.clock.timers, t) return ok } func (c *fakeClock) advance(d time.Duration) { c.mu.Lock() defer c.mu.Unlock() c.now = c.now.Add(d) for timer, at := range c.timers { if !at.After(c.now) { timer.ch <- c.now delete(c.timers, timer) } } } func receive[T any](t *testing.T, ch <-chan T) T { t.Helper() select { case v := <-ch: return v case <-time.After(5 * time.Second): t.Fatal("timed out waiting for test worker") var zero T return zero } }