// Package isolatedjobtest holds test helpers for isolatedjob: a clock a test // moves by hand and the contract suite every Runner must pass. package isolatedjobtest import ( "fmt" "sync" "time" ) // FakeClock is an isolatedjob.Clock that moves only when a test moves it. // Wall and Mono are set separately, so a test can move the calendar time back // while elapsed time moves forward. It is safe for concurrent use. type FakeClock struct { mu sync.Mutex wall time.Time mono time.Duration } // NewFakeClock returns a clock reading wall, with Mono at zero. func NewFakeClock(wall time.Time) *FakeClock { return &FakeClock{wall: wall} } // Wall returns the calendar time last set. func (c *FakeClock) Wall() time.Time { c.mu.Lock() defer c.mu.Unlock() return c.wall } // Mono returns the elapsed time so far. func (c *FakeClock) Mono() time.Duration { c.mu.Lock() defer c.mu.Unlock() return c.mono } // SetWall sets the calendar time to any value, earlier or later. Mono does // not move. func (c *FakeClock) SetWall(t time.Time) { c.mu.Lock() defer c.mu.Unlock() c.wall = t } // AdvanceMono moves elapsed time forward by d. Elapsed time never goes back, // so a negative d panics. Wall does not move. func (c *FakeClock) AdvanceMono(d time.Duration) { if d < 0 { panic(fmt.Sprintf("isolatedjobtest: AdvanceMono(%v): elapsed time never goes back", d)) } c.mu.Lock() defer c.mu.Unlock() c.mono += d }