52 lines
1.5 KiB
Go
52 lines
1.5 KiB
Go
// Package testutil holds small test helpers that several backend packages
|
|
// share. It has no production callers.
|
|
package testutil
|
|
|
|
import (
|
|
"sync"
|
|
"time"
|
|
)
|
|
|
|
// FakeClock is a manual application clock for tests. Code under test takes
|
|
// its Now method as its clock function, and the test moves time with
|
|
// Advance or Set instead of waiting, so a deadline days away is checked in
|
|
// microseconds. It is safe for concurrent use, so a worker goroutine can
|
|
// read it while the test moves it.
|
|
type FakeClock struct {
|
|
mu sync.Mutex
|
|
now time.Time
|
|
}
|
|
|
|
// NewFakeClock returns a clock that stands at start until it is moved.
|
|
func NewFakeClock(start time.Time) *FakeClock {
|
|
return &FakeClock{now: start}
|
|
}
|
|
|
|
// Now returns the current fake time. Its signature matches the
|
|
// func() time.Time clocks that the backend injects.
|
|
func (clock *FakeClock) Now() time.Time {
|
|
clock.mu.Lock()
|
|
defer clock.mu.Unlock()
|
|
return clock.now
|
|
}
|
|
|
|
// Advance moves the clock forward by step and returns the new time. A
|
|
// negative step panics, because application clocks are expected to be
|
|
// monotonic in tests; use Set to model a clock that jumps back.
|
|
func (clock *FakeClock) Advance(step time.Duration) time.Time {
|
|
if step < 0 {
|
|
panic("testutil.FakeClock.Advance - step must not be negative")
|
|
}
|
|
clock.mu.Lock()
|
|
defer clock.mu.Unlock()
|
|
clock.now = clock.now.Add(step)
|
|
return clock.now
|
|
}
|
|
|
|
// Set moves the clock to now, forward or back.
|
|
func (clock *FakeClock) Set(now time.Time) {
|
|
clock.mu.Lock()
|
|
defer clock.mu.Unlock()
|
|
clock.now = now
|
|
}
|