timeshim

package module
v0.0.0-...-021ae9a Latest Latest
Warning

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

Go to latest
Published: Nov 26, 2026 License: Apache-2.0 Imports: 6 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

timeshim

Injectable time for deterministic tests. Code that times out or expires in the background takes a timeshim.Clock instead of calling time.Now and time.AfterFunc; production uses the system clock, and tests move a fake clock instead of waiting. Standard library only.

go get github.com/djylb/timeshim

Production code

Accept a Clock and default to Real:

type Cache struct {
	Clock timeshim.Clock // nil means timeshim.Real
}

func (c *Cache) expireAfter(d time.Duration, f func()) timeshim.Timer {
	return timeshim.Or(c.Clock).AfterFunc(d, f)
}

A *time.Timer is a timeshim.Timer, so Real adds no wrapper. To switch clock implementations, declare var clk timeshim.Clock = timeshim.Real.

API

The Clock interface is two methods, Now and AfterFunc, so any clock is easy to supply. The rest of the time package is built on it as functions that take a clock, with the names and semantics of time:

Function Like
Since(c, t), Until(c, t) time.Since, time.Until
Sleep(ctx, c, d) time.Sleep, ending early with ctx
After(c, d) time.After
NewTimer(c, d) time.NewTimer
NewTicker(c, d) time.NewTicker
WithDeadline, WithTimeout context.WithDeadline, WithTimeout
WithDeadlineCause, WithTimeoutCause context.WithDeadlineCause, WithTimeoutCause

On Real these helpers use system timers and contexts directly. Sleep waits on a stoppable timer so cancellation can wake it. On other clocks, stop tickers when finished to release their registrations. Only a direct *Fake defers channel delivery until an advance ends. Wrappers, including types embedding *Fake, use their own Now and AfterFunc methods and deliver the scheduled time when the callback runs. Standard cancelable parents and parents implementing AfterFunc support cancellation propagation without a waiting goroutine. For other parents with a private Done channel, the context package may start a waiter until the parent or child ends.

Tests

clk := timeshim.NewFake(time.Unix(0, 0))
c := &Cache{Clock: clk}
go c.Run()

// Wait until the code under test has armed its timer, then fire it.
if err := clk.WaitPending(ctx, 1); err != nil {
	t.Fatal(err)
}
clk.Advance(time.Minute)
Fake method Does
Advance(d) moves forward by d, calling what comes due
AdvanceTo(t) moves forward to t; an earlier t does not move back
AdvanceToNext() jumps to the earliest pending time and fires it
Pending() counts the pending functions
Next() reports the earliest pending time
Deadlines() lists their times, earliest first
WaitPending(ctx, n) waits until n functions are pending
WaitDeadline(ctx, t) waits until a function is pending at t

Guarantees

  • Advance runs the functions that come due in its own goroutine, in order of their deadlines, outside the clock's lock, so a function may call the clock again or arm new timers; those run in the same Advance when due.
  • The channel of a ChanTimer or Ticker created directly on a *Fake receives the timer's time when the firing Advance ends: a goroutine it wakes finds the clock at its new time, as after a jump, and a timer that goroutine sets does not fire in the same Advance, however it is scheduled.
  • Equal deadlines fire in the order the timers were armed (AfterFunc or Reset).
  • Time never goes backwards: a negative Advance panics, and of concurrent calls each leaves the clock at least where it found it.
  • Timer.Stop and Timer.Reset match *time.Timer: each reports whether the call was still pending. ChanTimer and Ticker follow the channel semantics of time since Go 1.23: a timer that fired but whose value was not received still counts as pending, after Stop or Reset returns no stale value is received, and a ticker drops ticks a slow receiver misses.
  • For Fake.AfterFunc and its timer's Reset, a nonpositive delay is due at once: the function runs in the next Advance (Advance(0) included), not in a goroutine of its own, and Deadlines never reports a time before Now. A ChanTimer (or After) with such a delay has its value ready at once, as with time.NewTimer, since no function has to run.
  • The order holds within one Advance; concurrent Advance calls may run due functions at the same time in different goroutines.
  • WithDeadline on an ended parent, or with a past deadline, returns a context that has already ended, with the parent's error first.
  • A clock drives the deadline requested on it. When a parent deadline fires, its children inherit its error and cause, including through standard value and cancellation contexts. An independent clock can still reach a child's own requested deadline first. A parent wrapped in context.WithoutCancel supplies values without propagating cancellation.
  • The zero value of Fake starts at the zero time. It supports concurrent use and must not be copied after first use.
  • Each advance processes its own deferred deliveries even if a callback panics. Older ticks overtaken by a later delivery are dropped. The panic propagates with the clock at the latest time reached, including by nested advances.
  • On a fake clock, an unrepresentable target for relative advance, timeout, initial timer or ticker registration, or reset panics. A failed reset preserves the previous registration and any unread value. A running ticker retires after its last representable tick.

With testing/synctest

testing/synctest runs a test in a bubble whose time package is virtual, and advances it when every goroutine is blocked. Inside a bubble, Real is that virtual time, so code that takes a timeshim.Clock needs nothing special. timeshim covers what a bubble does not:

  • explicit control: move time by an exact step at a chosen point, or inspect what is pending, rather than waiting for the bubble to idle;
  • code that runs outside a bubble, such as goroutines started before the test or shared fixtures;
  • tests on real network I/O, which keeps a bubble from ever idling;
  • injecting time into production code, such as a clock that follows another source.

A Fake also works inside a bubble: a goroutine waiting on it is durably blocked, so synctest.Wait returns.

License

Apache-2.0

Documentation

Overview

Package timeshim provides injectable time for deterministic tests: code takes a Clock instead of calling time.Now and time.AfterFunc, production passes Real, and tests pass a Fake that moves only when told to. The package uses only the standard library.

Index

Constants

View Source
const Real realClock = 0

Real is the system clock.

Variables

This section is empty.

Functions

func After

func After(c Clock, d time.Duration) <-chan time.Time

After returns a channel that receives c's time once d has passed, as time.After.

func Since

func Since(c Clock, t time.Time) time.Duration

Since returns the time elapsed on c since t, as time.Since.

func Sleep

func Sleep(ctx context.Context, c Clock, d time.Duration) error

Sleep waits until d has passed on c and returns nil, or ctx's error if ctx ends first. A d of zero or less returns at once, with ctx's error if any.

func Until

func Until(c Clock, t time.Time) time.Duration

Until returns the duration on c until t, as time.Until.

func WithDeadline

func WithDeadline(ctx context.Context, c Clock, deadline time.Time) (context.Context, context.CancelFunc)

WithDeadline returns a copy of ctx that ends with context.DeadlineExceeded once c reaches deadline, as context.WithDeadline on the system clock. On a Fake the context ends within the Advance that reaches deadline. A ctx that has ended, or a deadline that has passed, gives a context that has ended already, with ctx's error first. The supplied clock drives the requested deadline even when ctx uses another clock. The context also ends when ctx does, or when the returned cancel is called. A parent with a private Done channel may require a waiting goroutine unless it implements AfterFunc.

func WithDeadlineCause

func WithDeadlineCause(ctx context.Context, c Clock, deadline time.Time, cause error) (context.Context, context.CancelFunc)

WithDeadlineCause is like context.WithDeadlineCause on c: when the deadline passes, Err reports context.DeadlineExceeded and context.Cause reports cause.

func WithTimeout

WithTimeout is like WithDeadline with a deadline d from now. On clocks other than Real it panics if that time cannot be represented.

func WithTimeoutCause

func WithTimeoutCause(ctx context.Context, c Clock, d time.Duration, cause error) (context.Context, context.CancelFunc)

WithTimeoutCause is like WithDeadlineCause with a deadline d from now. On clocks other than Real it panics if that time cannot be represented.

Types

type ChanTimer

type ChanTimer struct {
	C <-chan time.Time
	// contains filtered or unexported fields
}

ChanTimer is a timer that sends c's time on C once its time has passed, as a *time.Timer made by time.NewTimer. As with time.Timer since Go 1.23, C is unbuffered in effect: once Stop or Reset returns, no stale time is received from C.

func NewTimer

func NewTimer(c Clock, d time.Duration) *ChanTimer

NewTimer returns a timer that sends on its channel once d has passed on c, as time.NewTimer. On Real it is a *time.Timer underneath. On other clocks a d of zero or less has the value ready on C at once, as does Reset with such a d. A positive d with an unrepresentable target panics.

func (*ChanTimer) Reset

func (t *ChanTimer) Reset(d time.Duration) bool

Reset makes the timer fire d from now and reports whether it was pending, as (*time.Timer).Reset. On a Fake an unrepresentable target panics and preserves the previous registration and any unread value.

func (*ChanTimer) Stop

func (t *ChanTimer) Stop() bool

Stop prevents the timer from firing and reports whether it was pending, as (*time.Timer).Stop.

type Clock

type Clock interface {
	// Now returns the current time.
	Now() time.Time
	// AfterFunc calls f in its own goroutine, or for Fake in Advance,
	// once d has passed, as time.AfterFunc does.
	AfterFunc(d time.Duration, f func()) Timer
}

Clock tells the time and runs functions after a delay.

func Or

func Or(c Clock) Clock

Or returns c, or Real when c is nil.

type Fake

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

Fake is a clock that moves only by Advance. Its zero value starts at the zero time. It is safe for concurrent use and must not be copied after first use.

func NewFake

func NewFake(t time.Time) *Fake

NewFake returns a Fake clock at t.

func (*Fake) Advance

func (c *Fake) Advance(d time.Duration)

Advance moves the clock d forward and calls, in order of their times and outside the clock's lock, the functions that are due; a function may set new timers, which are called too when due. The channels of a ChanTimer or Ticker created directly on c receive the scheduled time when Advance ends, so a goroutine woken by one finds the clock at its new time, and no timer it sets fires in the same Advance. Functions due at the same time are called in the order they were armed by AfterFunc or Reset. Time never goes back. A negative d or an unrepresentable target panics. Of concurrent calls, each leaves the clock at least where it took it.

The order holds within one call. Concurrent calls take due functions from the same list, so their functions may run at the same time in different goroutines; drive a Fake from one goroutine to keep a single global order.

func (*Fake) AdvanceTo

func (c *Fake) AdvanceTo(t time.Time)

AdvanceTo moves the clock forward to t as Advance does. A t that is not after the clock's time only calls the functions already due.

func (*Fake) AdvanceToNext

func (c *Fake) AdvanceToNext() (time.Time, bool)

AdvanceToNext moves the clock to the earliest pending time, calls the functions due then as Advance does, and returns that time. It reports false, and leaves the clock alone, when no function is pending.

func (*Fake) AfterFunc

func (c *Fake) AfterFunc(d time.Duration, f func()) Timer

AfterFunc arranges for f to be called by the Advance that reaches d from now, in the goroutine of Advance. A d of zero or less is due at once: f is called by the next Advance, AdvanceTo or AdvanceToNext, Advance(0) included, rather than in a goroutine of its own as time.AfterFunc does, so that tests stay deterministic and f never runs under the Fake's lock.

Timer.Reset re-arms in the same way. A negative d counts as zero, so Deadlines never reports a time before Now. An unrepresentable target panics before the registration changes.

func (*Fake) Deadlines

func (c *Fake) Deadlines() []time.Time

Deadlines returns the times of the pending functions, earliest first.

func (*Fake) Next

func (c *Fake) Next() (time.Time, bool)

Next returns the earliest pending time, and false when no function is pending.

func (*Fake) Now

func (c *Fake) Now() time.Time

Now returns the clock's time.

func (*Fake) Pending

func (c *Fake) Pending() int

Pending returns the number of functions waiting for their time.

func (*Fake) WaitDeadline

func (c *Fake) WaitDeadline(ctx context.Context, t time.Time) error

WaitDeadline waits until a function is pending at exactly t, such as once code under test has armed the one timer a test is about to pass, and returns nil, or ctx's error if ctx ends first. Unlike WaitPending it does not depend on how many other timers are pending. It does not move the clock.

func (*Fake) WaitPending

func (c *Fake) WaitPending(ctx context.Context, n int) error

WaitPending waits until at least n functions wait for their time, such as once code under test running in another goroutine has armed its timers, and returns nil, or ctx's error if ctx ends first. It does not move the clock.

type Ticker

type Ticker struct {
	C <-chan time.Time
	// contains filtered or unexported fields
}

Ticker sends c's time on C every period, as a *time.Ticker: a tick that a slow receiver misses is dropped, and once Stop or Reset returns no stale tick is received.

func NewTicker

func NewTicker(c Clock, d time.Duration) *Ticker

NewTicker returns a ticker of period d on c, as time.NewTicker; d must be positive. On clocks other than Real an unrepresentable first tick panics. A Fake ticker retires after its last representable tick. Stop tickers on clocks other than Real to release the clock registration.

func (*Ticker) Reset

func (t *Ticker) Reset(d time.Duration)

Reset stops the ticker and restarts it with period d, as (*time.Ticker).Reset; d must be positive. On a Fake an unrepresentable first tick panics and leaves the ticker unchanged.

func (*Ticker) Stop

func (t *Ticker) Stop()

Stop turns the ticker off, as (*time.Ticker).Stop.

type Timer

type Timer interface {
	// Stop prevents the call and reports whether it was still pending.
	Stop() bool
	// Reset makes the call happen d from now and reports whether it was
	// still pending.
	Reset(d time.Duration) bool
}

Timer is a pending call of AfterFunc. A *time.Timer is one.

Jump to

Keyboard shortcuts

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