refactor: introduce clock to make tests reproducible
This commit is contained in:
28
internal/clock/clock.go
Normal file
28
internal/clock/clock.go
Normal file
@@ -0,0 +1,28 @@
|
||||
package clock
|
||||
|
||||
import "time"
|
||||
|
||||
// Clock is the time source injected into services.
|
||||
// Production code uses Real(); tests use Fixed().
|
||||
type Clock interface {
|
||||
Now() time.Time
|
||||
}
|
||||
|
||||
// Real returns a Clock backed by time.Now().
|
||||
func Real() Clock { return realClock{} }
|
||||
|
||||
type realClock struct{}
|
||||
|
||||
func (realClock) Now() time.Time { return time.Now() }
|
||||
|
||||
// FixedClock always returns T. Advance shifts T forward.
|
||||
// Intended for tests only.
|
||||
type FixedClock struct{ T time.Time }
|
||||
|
||||
// Fixed returns a *FixedClock set to t.
|
||||
func Fixed(t time.Time) *FixedClock { return &FixedClock{T: t} }
|
||||
|
||||
func (f *FixedClock) Now() time.Time { return f.T }
|
||||
|
||||
// Advance shifts the clock forward by d.
|
||||
func (f *FixedClock) Advance(d time.Duration) { f.T = f.T.Add(d) }
|
||||
Reference in New Issue
Block a user