clockwork

package module
v0.5.0 Latest Latest
Warning

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

Go to latest
Published: Nov 29, 2024 License: Apache-2.0 Imports: 6 Imported by: 2,613

README

clockwork

Mentioned in Awesome Go

GitHub Workflow Status Go Report Card Go Version go.dev reference

A simple fake clock for Go.

Usage

Replace uses of the time package with the clockwork.Clock interface instead.

For example, instead of using time.Sleep directly:

func myFunc() {
	time.Sleep(3 * time.Second)
	doSomething()
}

Inject a clock and use its Sleep method instead:

func myFunc(clock clockwork.Clock) {
	clock.Sleep(3 * time.Second)
	doSomething()
}

Now you can easily test myFunc with a FakeClock:

func TestMyFunc(t *testing.T) {
	ctx := context.Background()
	c := clockwork.NewFakeClock()

	// Start our sleepy function
	var wg sync.WaitGroup
	wg.Add(1)
	go func() {
		myFunc(c)
		wg.Done()
	}()

	// Ensure we wait until myFunc is waiting on the clock.
	// Use a context to avoid blocking forever if something
	// goes wrong.
	ctx, cancel := context.WithTimeout(ctx, 10*time.Second)
	defer cancel()
	c.BlockUntilContext(ctx, 1)

	assertState()

	// Advance the FakeClock forward in time
	c.Advance(3 * time.Second)

	// Wait until the function completes
	wg.Wait()

	assertState()
}

and in production builds, simply inject the real clock instead:

myFunc(clockwork.NewRealClock())

See example_test.go for a full example.

Credits

clockwork is inspired by @wickman's threaded fake clock, and the Golang playground

License

Apache License, Version 2.0. Please see License File for more information.

Documentation

Overview

Package clockwork contains a simple fake clock for Go.

Index

Constants

This section is empty.

Variables

View Source
var ErrFakeClockDeadlineExceeded error = fmt.Errorf("clockwork.FakeClock: %w", context.DeadlineExceeded)

ErrFakeClockDeadlineExceeded is the error returned by context.Context when the deadline passes on a context which uses a FakeClock.

It wraps a context.DeadlineExceeded error, i.e.:

// The following is true for any Context whose deadline has been exceeded,
// including contexts made with clockwork.WithDeadline or clockwork.WithTimeout.

errors.Is(ctx.Err(), context.DeadlineExceeded)

// The following can only be true for contexts made
// with clockwork.WithDeadline or clockwork.WithTimeout.

errors.Is(ctx.Err(), clockwork.ErrFakeClockDeadlineExceeded)

Functions

func AddToContext added in v0.2.3

func AddToContext(ctx context.Context, clock Clock) context.Context

AddToContext creates a derived context that references the specified clock.

Be aware this doesn't change the behavior of standard library functions, such as context.WithTimeout or context.WithDeadline. For this reason, users should prefer passing explicit clockwork.Clock variables rather can passing the clock via the context.

func WithDeadline added in v0.5.0

func WithDeadline(parent context.Context, clock Clock, t time.Time) (context.Context, context.CancelFunc)

WithDeadline returns a context with a deadline based on a FakeClock.

The returned context ignores parent cancelation if the parent was cancelled with a context.DeadlineExceeded error. Any other error returned by the parent is treated normally, cancelling the returned context.

If the parent is cancelled with a context.DeadlineExceeded error, the only way to then cancel the returned context is by calling the returned context.CancelFunc.

func WithTimeout added in v0.5.0

func WithTimeout(parent context.Context, clock Clock, d time.Duration) (context.Context, context.CancelFunc)

WithTimeout returns a context with a timeout based on a FakeClock.

The returned context follows the same behaviors as WithDeadline.

Types

type Clock

type Clock interface {
	After(d time.Duration) <-chan time.Time
	Sleep(d time.Duration)
	Now() time.Time
	Since(t time.Time) time.Duration
	Until(t time.Time) time.Duration
	NewTicker(d time.Duration) Ticker
	NewTimer(d time.Duration) Timer
	AfterFunc(d time.Duration, f func()) Timer
}

Clock provides an interface that packages can use instead of directly using the time module, so that chronology-related behavior can be tested.

func FromContext added in v0.2.3

func FromContext(ctx context.Context) Clock

FromContext extracts a clock from the context. If not present, a real clock is returned.

func NewRealClock

func NewRealClock() Clock

NewRealClock returns a Clock which simply delegates calls to the actual time package; it should be used by packages in production.

type FakeClock

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

FakeClock provides an interface for a clock which can be manually advanced through time.

FakeClock maintains a list of "waiters," which consists of all callers waiting on the underlying clock (i.e. Tickers and Timers including callers of Sleep or After). Users can call BlockUntil to block until the clock has an expected number of waiters.

func NewFakeClock

func NewFakeClock() *FakeClock

NewFakeClock returns a FakeClock implementation which can be manually advanced through time for testing. The initial time of the FakeClock will be the current system time.

Tests that require a deterministic time must use NewFakeClockAt.

func NewFakeClockAt

func NewFakeClockAt(t time.Time) *FakeClock

NewFakeClockAt returns a FakeClock initialised at the given time.Time.

func (*FakeClock) Advance

func (fc *FakeClock) Advance(d time.Duration)

Advance advances fakeClock to a new point in time, ensuring waiters and blockers are notified appropriately before returning.

func (*FakeClock) After added in v0.5.0

func (fc *FakeClock) After(d time.Duration) <-chan time.Time

After mimics time.After; it waits for the given duration to elapse on the fakeClock, then sends the current time on the returned channel.

func (*FakeClock) AfterFunc added in v0.5.0

func (fc *FakeClock) AfterFunc(d time.Duration, f func()) Timer

AfterFunc mimics time.AfterFunc; it returns a Timer that will invoke the given function only after calls to fakeClock.Advance() have moved the clock past the given duration.

func (*FakeClock) BlockUntil deprecated

func (fc *FakeClock) BlockUntil(n int)

BlockUntil blocks until the FakeClock has the given number of waiters.

Prefer BlockUntilContext in new code, which offers context cancellation to prevent deadlock.

Deprecated: New code should prefer BlockUntilContext.

func (*FakeClock) BlockUntilContext added in v0.5.0

func (fc *FakeClock) BlockUntilContext(ctx context.Context, n int) error

BlockUntilContext blocks until the fakeClock has the given number of waiters or the context is cancelled.

func (*FakeClock) NewTicker added in v0.5.0

func (fc *FakeClock) NewTicker(d time.Duration) Ticker

NewTicker returns a Ticker that will expire only after calls to FakeClock.Advance() have moved the clock past the given duration.

The duration d must be greater than zero; if not, NewTicker will panic.

func (*FakeClock) NewTimer added in v0.5.0

func (fc *FakeClock) NewTimer(d time.Duration) Timer

NewTimer returns a Timer that will fire only after calls to fakeClock.Advance() have moved the clock past the given duration.

func (*FakeClock) Now added in v0.5.0

func (fc *FakeClock) Now() time.Time

Now returns the current time of the fakeClock

func (*FakeClock) Since added in v0.5.0

func (fc *FakeClock) Since(t time.Time) time.Duration

Since returns the duration that has passed since the given time on the fakeClock.

func (*FakeClock) Sleep added in v0.5.0

func (fc *FakeClock) Sleep(d time.Duration)

Sleep blocks until the given duration has passed on the fakeClock.

func (*FakeClock) Until added in v0.5.0

func (fc *FakeClock) Until(t time.Time) time.Duration

Until returns the duration that has to pass from the given time on the fakeClock to reach the given time.

type Ticker added in v0.2.0

type Ticker interface {
	Chan() <-chan time.Time
	Reset(d time.Duration)
	Stop()
}

Ticker provides an interface which can be used instead of directly using time.Ticker. The real-time ticker t provides ticks through t.C which becomes t.Chan() to make this channel requirement definable in this interface.

type Timer added in v0.3.0

type Timer interface {
	Chan() <-chan time.Time
	Reset(d time.Duration) bool
	Stop() bool
}

Timer provides an interface which can be used instead of directly using time.Timer. The real-time timer t provides events through t.C which becomes t.Chan() to make this channel requirement definable in this interface.

Jump to

Keyboard shortcuts

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