clock

package
v0.0.6-alpha Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jul 15, 2026 License: MIT Imports: 3 Imported by: 0

Documentation

Overview

Package clock provides an injectable time source for testable code.

Consumers that need to advance time in tests hold a Clock rather than calling time.Now directly. Production uses Real; tests use Frozen. Both satisfy the Clock interface.

Package-level Now/Since/Sleep back onto a swappable default so consumers who do not want to thread a Clock through their code can still substitute one in tests via SetDefault.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Now

func Now() time.Time

Now returns the current time from the default clock.

func SetDefault

func SetDefault(c Clock)

SetDefault installs c as the package-level clock. Test setup functions typically call SetDefault(NewFrozen(...)) then restore Real on cleanup.

func Since

func Since(t time.Time) time.Duration

Since returns the elapsed time since t from the default clock.

func Sleep

func Sleep(d time.Duration)

Sleep pauses using the default clock.

Types

type Clock

type Clock interface {
	Now() time.Time
	Since(t time.Time) time.Duration
	Sleep(d time.Duration)
}

Clock is the injectable time source.

func Default

func Default() Clock

Default returns the current package-level clock.

func NewReal

func NewReal() Clock

NewReal returns the singleton real clock.

type Frozen

type Frozen struct {
	// contains filtered or unexported fields
}

Frozen is a Clock whose Now advances only when Advance is called. Sleep is a no-op unless Advance runs concurrently. Safe for concurrent use.

func NewFrozen

func NewFrozen(t time.Time) *Frozen

NewFrozen returns a Frozen clock initialised to t.

func (*Frozen) Advance

func (f *Frozen) Advance(d time.Duration)

Advance moves the frozen clock forward by d.

func (*Frozen) Now

func (f *Frozen) Now() time.Time

Now returns the current frozen time.

func (*Frozen) Set

func (f *Frozen) Set(t time.Time)

Set overrides the current time (useful for scenario tests).

func (*Frozen) Since

func (f *Frozen) Since(t time.Time) time.Duration

Since returns the difference between the frozen now and t.

func (*Frozen) Sleep

func (f *Frozen) Sleep(time.Duration)

Sleep is a no-op on the frozen clock. Tests that expect Sleep to influence time should call Advance instead.

type Real

type Real struct{}

Real is a Clock backed by the standard time package.

func (Real) Now

func (Real) Now() time.Time

Now returns the current wall time.

func (Real) Since

func (Real) Since(t time.Time) time.Duration

Since returns time since t.

func (Real) Sleep

func (Real) Sleep(d time.Duration)

Sleep pauses the caller for d.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL