Download this file
| 1 | // Package isolatedjobtest holds test helpers for isolatedjob: a clock a test |
| 2 | // moves by hand and the contract suite every Runner must pass. |
| 3 | package isolatedjobtest |
| 4 | |
| 5 | import ( |
| 6 | "fmt" |
| 7 | "sync" |
| 8 | "time" |
| 9 | ) |
| 10 | |
| 11 | // FakeClock is an isolatedjob.Clock that moves only when a test moves it. |
| 12 | // Wall and Mono are set separately, so a test can move the calendar time back |
| 13 | // while elapsed time moves forward. It is safe for concurrent use. |
| 14 | type FakeClock struct { |
| 15 | mu sync.Mutex |
| 16 | wall time.Time |
| 17 | mono time.Duration |
| 18 | } |
| 19 | |
| 20 | // NewFakeClock returns a clock reading wall, with Mono at zero. |
| 21 | func NewFakeClock(wall time.Time) *FakeClock { |
| 22 | return &FakeClock{wall: wall} |
| 23 | } |
| 24 | |
| 25 | // Wall returns the calendar time last set. |
| 26 | func (c *FakeClock) Wall() time.Time { |
| 27 | c.mu.Lock() |
| 28 | defer c.mu.Unlock() |
| 29 | return c.wall |
| 30 | } |
| 31 | |
| 32 | // Mono returns the elapsed time so far. |
| 33 | func (c *FakeClock) Mono() time.Duration { |
| 34 | c.mu.Lock() |
| 35 | defer c.mu.Unlock() |
| 36 | return c.mono |
| 37 | } |
| 38 | |
| 39 | // SetWall sets the calendar time to any value, earlier or later. Mono does |
| 40 | // not move. |
| 41 | func (c *FakeClock) SetWall(t time.Time) { |
| 42 | c.mu.Lock() |
| 43 | defer c.mu.Unlock() |
| 44 | c.wall = t |
| 45 | } |
| 46 | |
| 47 | // AdvanceMono moves elapsed time forward by d. Elapsed time never goes back, |
| 48 | // so a negative d panics. Wall does not move. |
| 49 | func (c *FakeClock) AdvanceMono(d time.Duration) { |
| 50 | if d < 0 { |
| 51 | panic(fmt.Sprintf("isolatedjobtest: AdvanceMono(%v): elapsed time never goes back", d)) |
| 52 | } |
| 53 | c.mu.Lock() |
| 54 | defer c.mu.Unlock() |
| 55 | c.mono += d |
| 56 | } |
| 57 | |