testy: make safe for concurrent use.

Signed-off-by: David Anderson <dave@natulte.net>
reviewable/pr232/r1
David Anderson 5 years ago
parent 1fdadf06f1
commit 80261b02ba

@ -4,7 +4,10 @@
package testy package testy
import "time" import (
"sync"
"time"
)
// Clock is a testing clock that advances every time its Now method is // Clock is a testing clock that advances every time its Now method is
// called, beginning at Start. // called, beginning at Start.
@ -18,11 +21,15 @@ type Clock struct {
Step time.Duration Step time.Duration
// Present is the time that the next Now call will receive. // Present is the time that the next Now call will receive.
Present time.Time Present time.Time
sync.Mutex
} }
// Now returns the virtual clock's current time, and avances it // Now returns the virtual clock's current time, and avances it
// according to its step configuration. // according to its step configuration.
func (c *Clock) Now() time.Time { func (c *Clock) Now() time.Time {
c.Lock()
defer c.Unlock()
if c.Start.IsZero() { if c.Start.IsZero() {
c.Start = time.Now() c.Start = time.Now()
c.Present = c.Start c.Present = c.Start
@ -35,5 +42,7 @@ func (c *Clock) Now() time.Time {
// Reset rewinds the virtual clock to its start time. // Reset rewinds the virtual clock to its start time.
func (c *Clock) Reset() { func (c *Clock) Reset() {
c.Lock()
defer c.Unlock()
c.Present = c.Start c.Present = c.Start
} }

Loading…
Cancel
Save