clock

package module
v0.1.6 Latest Latest
Warning

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

Go to latest
Published: Jul 2, 2019 License: MIT Imports: 3 Imported by: 1

README

clock GoDoc Build Status codecov

Clock is a library for mocking the time package in go. It supports mocking time.Timer and time.Ticker for testing purposes.

This library is heavily inspired by benbjohnson/clock and jonboulle/clockwork.

Usage

Instead of time, use the clock.Clock interface. In your real application, you can call clock.New() to get the actual instance. For testing purposes, call clock.NewMock().

import (
	"testing"

	"github.com/leononame/clock"
)
func TestApp_Do(t *testing.T) {
    clock := clock.NewMock()
    context := Context{Clock: clock}
}

The interface exposes standard time functions that can be used like usual.

import (
    "time"

    "github.com/leononame/clock"
)

func timer() {
    c := clock.NewMock() // or clock.New()
    t := c.NewTicker(time.Second)
    now := c.Now()
}

Documentation

Overview

Package clock provides an abstraction layer around tickers. These abstraction layers can be used during testing tock mock ticking behaviour.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Clock

type Clock interface {
	// After waits for the duration to elapse and then sends the current time on the returned channel.
	After(d time.Duration) <-chan time.Time
	// AfterFunc waits for the duration to elapse and then executes a function.
	// A Timer is returned that can be stopped.
	AfterFunc(d time.Duration, fn func()) Timer
	// Now returns the current local time.
	Now() time.Time
	// Since returns the time elapsed since t.
	Since(time.Time) time.Duration
	// Until returns the duration until t.
	Until(time.Time) time.Duration
	// Sleep pauses the current goroutine for at least the duration d.
	// A negative or zero duration causes Sleep to return immediately.
	Sleep(time.Duration)
	// NewTicker returns a new Ticker containing a channel that will send the
	// time with a period specified by the duration argument.
	NewTicker(d time.Duration) Ticker
	// NewTimer creates a new Timer that will send
	// the current time on its channel after at least duration d.
	NewTimer(d time.Duration) Timer
}

Clock provides an abstraction for often-used time functions

func New

func New() Clock

New returns a Clock implementation based on the time package and is good for usage in deployed applications.

type Executer added in v0.1.1

type Executer interface {
	// NextExecution returns the next execution time
	NextExecution() time.Time
	// Execute executes the Executer object
	Execute(time.Time)
}

Executer is an interface that allows the fake clock implementation to abstract Timer and Ticker. This way, both types can be united in the same slice and thus be sorted by their next execution

type Mock

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

Mock is a type used for mocking the time package during tests.

func NewMock

func NewMock() *Mock

NewMock returns a Mock which implements Clock. It can be used to mock the current time in tests. When a new Mock is created, it starts with Unix timestamp 0.

func (*Mock) After

func (m *Mock) After(d time.Duration) <-chan time.Time

After behaves like time.After. However, it only fires when the internal time is forwarded by at least d.

func (*Mock) AfterFunc added in v0.1.1

func (m *Mock) AfterFunc(d time.Duration, fn func()) Timer

AfterFunc waits for the duration to elapse and then executes a function. A Timer is returned that can be stopped.

func (*Mock) Forward

func (m *Mock) Forward(d time.Duration)

Forward moves the internal time forward by the amount specified. Any timers or tickers that fire during that time period will be activated

func (*Mock) Len added in v0.1.1

func (m *Mock) Len() int

Len returns the number of internal Timers or Tickers that are being tracked.

func (*Mock) Less added in v0.1.1

func (m *Mock) Less(i, j int) bool

Less indicates whether Executer at position i should be executed before Executer at position j

func (*Mock) NewTicker

func (m *Mock) NewTicker(d time.Duration) Ticker

NewTicker returns a new Ticker containing a channel that will send the time with a period specified by the duration argument.

func (*Mock) NewTimer

func (m *Mock) NewTimer(d time.Duration) Timer

NewTimer creates a new Timer that will send the current time on its channel after at least duration d.

func (*Mock) Now

func (m *Mock) Now() time.Time

Now returns the current internal time as either set by Set() or forwarded by Forward().

func (*Mock) RunUntilDone added in v0.1.2

func (m *Mock) RunUntilDone()

RunUntilDone sets the internal time to the point in time where the latest timer will be fired. This means, all After() and AfterFunc() calls will have fired. Since tickers potentially run forever, they aren't included.

func (*Mock) Set

func (m *Mock) Set(t time.Time)

Set sets the internal time to a specific point in time. Any timers or tickers that fire during that time period will be activated

func (*Mock) Since

func (m *Mock) Since(t time.Time) time.Duration

Since returns the time elapsed since t in comparison to the internal time.

func (*Mock) Sleep

func (m *Mock) Sleep(d time.Duration)

Sleep pauses the current goroutine for at least the duration d in comparison to the internal time.

func (*Mock) Swap added in v0.1.1

func (m *Mock) Swap(i, j int)

Swap swaps the elements at i and j in the internal tracker for Timers and Tickers

func (*Mock) Until

func (m *Mock) Until(t time.Time) time.Duration

Until returns the duration until t in comparison to the internal time.

type Ticker

type Ticker interface {
	// Chan returns the readonly channel of the ticker
	Chan() <-chan time.Time
	// Stop stops the ticker. No more events will be sent through the channel
	Stop()
}

Ticker is an abstraction for the type time.Ticker that can be mocked for tests.

type Timer

type Timer interface {
	// Chan returns the readonly channel of the ticker
	Chan() <-chan time.Time

	// Stop prevents the Timer from firing.
	// It returns true if the call stops the timer, false if the timer has already
	// expired or been stopped.
	// Stop does not close the channel, to prevent a read from the channel succeeding
	// incorrectly.
	//
	// From the official docs:
	// To prevent a timer created with NewTimer from firing after a call to Stop,
	// check the return value and drain the channel.
	// For example, assuming the program has not received from t.C already:
	//
	// 	if !t.Stop() {
	// 		<-t.C
	// 	}
	//
	// This cannot be done concurrent to other receives from the Timer's
	// channel.
	//
	// For a timer created with AfterFunc(d, f), if t.Stop returns false, then the timer
	// has already expired and the function f has been started in its own goroutine;
	// Stop does not wait for f to complete before returning.
	// If the caller needs to know whether f is completed, it must coordinate
	// with f explicitly.
	Stop() bool

	// Reset changes the timer to expire after duration d.
	// It returns true if the timer had been active, false if the timer had
	// expired or been stopped.
	//
	// From the official docs:
	// Resetting a timer must take care not to race with the send into t.C
	// that happens when the current timer expires.
	// If a program has already received a value from t.C, the timer is known
	// to have expired, and t.Reset can be used directly.
	// If a program has not yet received a value from t.C, however,
	// the timer must be stopped and—if Stop reports that the timer expired
	// before being stopped—the channel explicitly drained:
	//
	// 	if !t.Stop() {
	// 		<-t.C
	// 	}
	// 	t.Reset(d)
	//
	// This should not be done concurrent to other receives from the Timer's
	// channel.
	//
	// Note that it is not possible to use Reset's return value correctly, as there
	// is a race condition between draining the channel and the new timer expiring.
	// Reset should always be invoked on stopped or expired channels, as described above.
	// The return value exists to preserve compatibility with existing programs.
	Reset(time.Duration) bool
}

Timer is an abstraction for the type time.Timer that can be mocked for tests.

Jump to

Keyboard shortcuts

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