Documentation
¶
Overview ¶
Package clock provides a Clock interface with a real implementation (backed by time.Now) and a controllable mock implementation for deterministic tests.
Any package that calls time.Now() or time.Since() directly cannot be tested deterministically. By accepting a Clock the package becomes trivially testable: inject clock.Real() in production, clock.NewMock(t0) in tests, advance with mock.Advance(d).
Usage — production:
type Worker struct { clk clock.Clock }
func New() *Worker { return &Worker{clk: clock.Real()} }
func (w *Worker) Age(t time.Time) time.Duration { return w.clk.Since(t) }
Usage — test:
mc := clock.NewMock(time.Unix(0, 0))
w := &Worker{clk: mc}
mc.Advance(5 * time.Minute)
// w.Age(...) now returns a deterministic value
Index ¶
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type Clock ¶
type Clock interface {
// Now returns the current (or mocked) time.
Now() time.Time
// Since returns the time elapsed since t (equivalent to Now().Sub(t)).
Since(t time.Time) time.Duration
// After returns a channel that fires after duration d. On the real
// clock this is time.After; on the mock it fires when the mock
// time is advanced past the deadline.
After(d time.Duration) <-chan time.Time
}
Clock is the interface satisfied by both Real and Mock. Any code that needs testable time handling should accept a Clock.
type Mock ¶
type Mock struct {
// contains filtered or unexported fields
}
Mock is a controllable Clock for use in tests. All methods are safe for concurrent use. Advance moves the clock forward, firing any timers whose deadline has been reached.
func NewMock ¶
NewMock returns a Mock clock initialised to start. Use time.Unix(0,0) or a known UTC instant for fully deterministic tests.
Example ¶
Code that takes a clock.Clock can be driven by a Mock in tests.
package main
import (
"fmt"
"time"
"github.com/baditaflorin/go-common/clock"
)
func main() {
m := clock.NewMock(time.Date(2026, 10, 17, 12, 0, 0, 0, time.UTC))
start := m.Now()
m.Advance(90 * time.Second)
fmt.Println(m.Since(start))
}
Output: 1m30s
func (*Mock) Advance ¶
Advance moves the mock clock forward by d and fires any timers whose deadline has been reached. d must be positive; negative values are a no-op.
func (*Mock) After ¶
After returns a channel that will receive the mock time once m.Advance moves the clock past m.Now().Add(d).