1
0
times/lib.go
2026-03-04 21:22:12 +01:00

61 lines
1.8 KiB
Go

// Package times provides a clock interface with implementations for production and testing code.
package times
import "time"
// Clock defines an interface with primitives for time related functionality.
type Clock interface {
// Now returns the current time.
Now() time.Time
// After returns a channel that can be used to receive the current time once, after the specified
// duration has passed.
After(time.Duration) <-chan time.Time
}
// TestClock is a test implementation of the Clock interface. On top of the Clock methods, it adds the
// possibility to manually step time or to virtually jump to a specified time.
type TestClock struct{
clock test
}
// Sys returns the Clock implementation based on the standard library time functions. Meant to be used with
// production code.
func Sys() Clock {
return sys{}
}
// Test creates a Clock implementation with manual time stepping function. Meant to be used with testing code.
func Test() TestClock {
var zero time.Time
return TestFrom(zero)
}
// TestFrom creates a Clock implementation with manual time stepping function, starting from the specified time.
// Meant to be used with testing code.
func TestFrom(t time.Time) TestClock {
return TestClock{clock: makeTestClock(t)}
}
// Now returns the current test time.
func (c TestClock) Now() time.Time {
return c.clock.now()
}
// After returns a channel that communicates the current time if the specified duration has passed.
func (c TestClock) After(d time.Duration) <-chan time.Time {
return c.clock.after(d)
}
// Pass turns the clock forward by d duration. Negative d is considered as 0.
func (c TestClock) Pass(d time.Duration) {
c.clock.pass(d)
}
// Jump sets the clock to time specified by t. Values of t in the past, relative to TestClock's current time,
// are ignored.
func (c TestClock) Jump(t time.Time) {
c.clock.jump(t)
}