2020-03-19 00:37:15 +00:00
|
|
|
// Copyright (c) 2020 Tailscale Inc & AUTHORS All rights reserved.
|
|
|
|
// Use of this source code is governed by a BSD-style
|
|
|
|
// license that can be found in the LICENSE file.
|
|
|
|
|
2020-04-29 03:56:11 +01:00
|
|
|
package tstest
|
2020-03-19 00:37:15 +00:00
|
|
|
|
2020-03-27 10:05:25 +00:00
|
|
|
import (
|
|
|
|
"sync"
|
|
|
|
"time"
|
|
|
|
)
|
2020-03-19 00:37:15 +00:00
|
|
|
|
|
|
|
// Clock is a testing clock that advances every time its Now method is
|
|
|
|
// called, beginning at Start.
|
|
|
|
//
|
|
|
|
// The zero value starts virtual time at an arbitrary value recorded
|
2020-03-27 07:38:11 +00:00
|
|
|
// in Start on the first call to Now, and time never advances.
|
2020-03-19 00:37:15 +00:00
|
|
|
type Clock struct {
|
|
|
|
// Start is the first value returned by Now.
|
|
|
|
Start time.Time
|
|
|
|
// Step is how much to advance with each Now call.
|
|
|
|
Step time.Duration
|
|
|
|
// Present is the time that the next Now call will receive.
|
|
|
|
Present time.Time
|
2020-03-27 10:05:25 +00:00
|
|
|
|
|
|
|
sync.Mutex
|
2020-03-19 00:37:15 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// Now returns the virtual clock's current time, and avances it
|
|
|
|
// according to its step configuration.
|
|
|
|
func (c *Clock) Now() time.Time {
|
2020-03-27 10:05:25 +00:00
|
|
|
c.Lock()
|
|
|
|
defer c.Unlock()
|
2020-07-11 06:16:36 +01:00
|
|
|
c.initLocked()
|
|
|
|
step := c.Step
|
|
|
|
ret := c.Present
|
|
|
|
c.Present = c.Present.Add(step)
|
|
|
|
return ret
|
|
|
|
}
|
|
|
|
|
|
|
|
func (c *Clock) Advance(d time.Duration) {
|
|
|
|
c.Lock()
|
|
|
|
defer c.Unlock()
|
|
|
|
c.initLocked()
|
|
|
|
c.Present = c.Present.Add(d)
|
|
|
|
}
|
|
|
|
|
|
|
|
func (c *Clock) initLocked() {
|
2020-03-19 00:37:15 +00:00
|
|
|
if c.Start.IsZero() {
|
|
|
|
c.Start = time.Now()
|
2020-04-17 21:19:41 +01:00
|
|
|
}
|
|
|
|
if c.Present.Before(c.Start) {
|
2020-03-19 00:37:15 +00:00
|
|
|
c.Present = c.Start
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Reset rewinds the virtual clock to its start time.
|
|
|
|
func (c *Clock) Reset() {
|
2020-03-27 10:05:25 +00:00
|
|
|
c.Lock()
|
|
|
|
defer c.Unlock()
|
2020-03-19 00:37:15 +00:00
|
|
|
c.Present = c.Start
|
|
|
|
}
|