clock

package module
v0.0.0-...-9e14626 Latest Latest
Warning

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

Go to latest
Published: May 26, 2016 License: MIT Imports: 3 Imported by: 186

README

clock Build Status Coverage Status GoDoc Project status

Clock is a small library for mocking time in Go. It provides an interface around the standard library's time package so that the application can use the realtime clock while tests can use the mock clock.

Usage

Realtime Clock

Your application can maintain a Clock variable that will allow realtime and mock clocks to be interchangable. For example, if you had an Application type:

import "github.com/andres-erbsen/clock"

type Application struct {
	Clock clock.Clock
}

You could initialize it to use the realtime clock like this:

var app Application
app.Clock = clock.New()
...

Then all timers and time-related functionality should be performed from the Clock variable.

Mocking time

In your tests, you will want to use a Mock clock:

import (
	"testing"

	"github.com/andres-erbsen/clock"
)

func TestApplication_DoSomething(t *testing.T) {
	mock := clock.NewMock()
	app := Application{Clock: mock}
	...
}

Now that you've initialized your application to use the mock clock, you can adjust the time programmatically. The mock clock always starts from the Unix epoch (midnight, Jan 1, 1970 UTC).

Controlling time

The mock clock provides the same functions that the standard library's time package provides. For example, to find the current time, you use the Now() function:

mock := clock.NewMock()

// Find the current time.
mock.Now().UTC() // 1970-01-01 00:00:00 +0000 UTC

// Move the clock forward.
mock.Add(2 * time.Hour)

// Check the time again. It's 2 hours later!
mock.Now().UTC() // 1970-01-01 02:00:00 +0000 UTC

Timers and Tickers are also controlled by this same mock clock. They will only execute when the clock is moved forward:

mock := clock.NewMock()
count := 0

// Kick off a timer to increment every 1 mock second.
go func() {
    ticker := clock.Ticker(1 * time.Second)
    for {
        <-ticker.C
        count++
    }
}()
runtime.Gosched()

// Move the clock forward 10 second.
mock.Add(10 * time.Second)

// This prints 10.
fmt.Println(count)

Documentation

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Clock

type Clock interface {
	After(d time.Duration) <-chan time.Time
	AfterFunc(d time.Duration, f func()) *Timer
	Now() time.Time
	Sleep(d time.Duration)
	Tick(d time.Duration) <-chan time.Time
	Ticker(d time.Duration) *Ticker
	Timer(d time.Duration) *Timer
}

Clock represents an interface to the functions in the standard library time package. Two implementations are available in the clock package. The first is a real-time clock which simply wraps the time package's functions. The second is a mock clock which will only make forward progress when programmatically adjusted.

func New

func New() Clock

New returns an instance of a real-time clock.

type Mock

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

Mock represents a mock clock that only moves forward programmically. It can be preferable to a real-time clock when testing time-based functionality.

func NewMock

func NewMock() *Mock

NewMock returns an instance of a mock clock. The current time of the mock clock on initialization is the Unix epoch.

func (*Mock) Add

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

Add moves the current time of the mock clock forward by the duration. This should only be called from a single goroutine at a time.

func (*Mock) After

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

After waits for the duration to elapse and then sends the current time on the returned channel.

Example
// Create a new mock clock.
clock := NewMock()
count := 0

ready := make(chan struct{})
// Create a channel to execute after 10 mock seconds.
go func() {
	ch := clock.After(10 * time.Second)
	close(ready)
	<-ch
	count = 100
}()
<-ready

// Print the starting value.
fmt.Printf("%s: %d\n", clock.Now().UTC(), count)

// Move the clock forward 5 seconds and print the value again.
clock.Add(5 * time.Second)
fmt.Printf("%s: %d\n", clock.Now().UTC(), count)

// Move the clock forward 5 seconds to the tick time and check the value.
clock.Add(5 * time.Second)
fmt.Printf("%s: %d\n", clock.Now().UTC(), count)
Output:

1970-01-01 00:00:00 +0000 UTC: 0
1970-01-01 00:00:05 +0000 UTC: 0
1970-01-01 00:00:10 +0000 UTC: 100

func (*Mock) AfterFunc

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

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

Example
// Create a new mock clock.
clock := NewMock()
count := 0

// Execute a function after 10 mock seconds.
clock.AfterFunc(10*time.Second, func() {
	count = 100
})
gosched()

// Print the starting value.
fmt.Printf("%s: %d\n", clock.Now().UTC(), count)

// Move the clock forward 10 seconds and print the new value.
clock.Add(10 * time.Second)
fmt.Printf("%s: %d\n", clock.Now().UTC(), count)
Output:

1970-01-01 00:00:00 +0000 UTC: 0
1970-01-01 00:00:10 +0000 UTC: 100

func (*Mock) Now

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

Now returns the current wall time on the mock clock.

func (*Mock) Set

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

Sets the current time of the mock clock to a specific one. This should only be called from a single goroutine at a time.

func (*Mock) Sleep

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

Sleep pauses the goroutine for the given duration on the mock clock. The clock must be moved forward in a separate goroutine.

Example
// Create a new mock clock.
clock := NewMock()
count := 0

// Execute a function after 10 mock seconds.
go func() {
	clock.Sleep(10 * time.Second)
	count = 100
}()
gosched()

// Print the starting value.
fmt.Printf("%s: %d\n", clock.Now().UTC(), count)

// Move the clock forward 10 seconds and print the new value.
clock.Add(10 * time.Second)
fmt.Printf("%s: %d\n", clock.Now().UTC(), count)
Output:

1970-01-01 00:00:00 +0000 UTC: 0
1970-01-01 00:00:10 +0000 UTC: 100

func (*Mock) Tick

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

Tick is a convenience function for Ticker(). It will return a ticker channel that cannot be stopped.

func (*Mock) Ticker

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

Ticker creates a new instance of Ticker.

Example
// Create a new mock clock.
clock := NewMock()
count := 0

ready := make(chan struct{})
// Increment count every mock second.
go func() {
	ticker := clock.Ticker(1 * time.Second)
	close(ready)
	for {
		<-ticker.C
		count++
	}
}()
<-ready

// Move the clock forward 10 seconds and print the new value.
clock.Add(10 * time.Second)
fmt.Printf("Count is %d after 10 seconds\n", count)

// Move the clock forward 5 more seconds and print the new value.
clock.Add(5 * time.Second)
fmt.Printf("Count is %d after 15 seconds\n", count)
Output:

Count is 10 after 10 seconds
Count is 15 after 15 seconds

func (*Mock) Timer

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

Timer creates a new instance of Timer.

Example
// Create a new mock clock.
clock := NewMock()
count := 0

ready := make(chan struct{})
// Increment count after a mock second.
go func() {
	timer := clock.Timer(1 * time.Second)
	close(ready)
	<-timer.C
	count++
}()
<-ready

// Move the clock forward 10 seconds and print the new value.
clock.Add(10 * time.Second)
fmt.Printf("Count is %d after 10 seconds\n", count)
Output:

Count is 1 after 10 seconds

type Ticker

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

Ticker holds a channel that receives "ticks" at regular intervals.

func (*Ticker) Stop

func (t *Ticker) Stop()

Stop turns off the ticker.

type Timer

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

Timer represents a single event. The current time will be sent on C, unless the timer was created by AfterFunc.

func (*Timer) Reset

func (t *Timer) Reset(d time.Duration) 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.

func (*Timer) Stop

func (t *Timer) Stop() bool

Stop turns off the timer.

Jump to

Keyboard shortcuts

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