modulepackage
1.0.2
Repository: https://github.com/michalkurzeja/go-clock.git
Documentation: pkg.go.dev
# README
go-clock
A small package that offers testable time functions.
Why?
It is hard to properly test the code that performs time operations relative to the current time
or that depends on the time flow, e.g. with time.Now()
or time.After(d)
calls.
go-clock
provides a package-level Clock object that can easily be swapped for a configurable mock in your tests.
The package also offers some commonly-used functions from the time
package that use the Clock
.
Installation
go get github.com/michalkurzeja/go-clock
Usage
In your code, simply use the go-clock
functions for time retrieval instead of the standard time
package:
import "github.com/michalkurzeja/go-clock"
now := clock.Now() // Instead of `time.Now()`
since := clock.Since(now) // Instead of `time.Since()`
c := clock.After(time.Second) // Instead of `time.After(time.Second)`
In your tests, you can mock the clock to get predictable time output:
fakeNow := time.Date(...)
mock := clock.Mock(fakeNow) // `clock.Now()` will always return `fakeNow` time.
defer clock.Restore()
mock.Add(time.Second) // Advances the fake clock's time by a second.
go-clock
uses the clock implementation from the benbjohnson/clock package.
For more details on the usage of the clock, please see it's docs.
# Functions
After waits for the duration to elapse and then sends the current time.
AfterFunc waits for the duration to elapse and then calls f in its own goroutine.
Mock replaces the Clock with a mock frozen at the given time and returns it.
Now returns the current local time.
Restore replaces the Clock with the real clock.
Since returns the time elapsed since t.
Sleep pauses the current goroutine for at least the duration d.
Tick is a convenience wrapper for NewTicker providing access to the ticking channel only.
Ticker returns a new Ticker containing a channel that will send the time with a period specified by the duration argument.
Timer creates a new Timer that will send the current time on its channel after at least duration d.
# Variables
Clock represents a global clock.