clock

package module
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Nov 5, 2026 License: MIT Imports: 2 Imported by: 1

README

go-clock

go-clock gives Go code the current time through an interface, so a test can set the time instead of waiting for it.

Code that calls time.Now directly is hard to test. A test can't check what happens when a token expires without sleeping until it does. With go-clock, the code asks a clock.Service for the time. In production that's the system clock, and in a test it's a mock clock that you set.

Install

go get github.com/The127/go-clock

Use it

Pass the clock to the code that needs the time:

type Tokens struct {
	clock clock.Service
}

func NewTokens(c clock.Service) *Tokens {
	return &Tokens{clock: c}
}

func (t *Tokens) Expired(expiry time.Time) bool {
	return t.clock.Now().After(expiry)
}

In production code, give it the system clock:

tokens := NewTokens(clock.NewSystemClock())

In a test, give it a mock clock and move its time forward:

func TestTokensExpire(t *testing.T) {
	start := time.Date(2025, 1, 1, 12, 0, 0, 0, time.UTC)
	mock, setTime := clock.NewMockClock(start)
	tokens := NewTokens(mock)

	setTime(start.Add(2 * time.Hour))

	if !tokens.Expired(start.Add(time.Hour)) {
		t.Error("the token should have expired")
	}
}

NewMockClock returns the clock and a function that sets its time. You can call both from several goroutines at once.

go-clock has no dependencies outside Go's standard library.

Contribute

CONTRIBUTING.md explains how to set up the tools, how to sign off your commits and how releases work.

License

go-clock is licensed under the MIT License.

Documentation

Overview

Package clock tells the time through an interface, so tests can set it.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func NewMockClock

func NewMockClock(now time.Time) (Service, TimeSetterFn)

NewMockClock returns a clock that always returns now, and a function that changes the time it returns. Both are safe to call from several goroutines.

Types

type Service

type Service interface {
	Now() time.Time
}

Service tells the current time.

func NewSystemClock

func NewSystemClock() Service

NewSystemClock returns a clock that returns time.Now.

type TimeSetterFn

type TimeSetterFn func(time.Time)

TimeSetterFn sets the time that a mock clock returns.

Jump to

Keyboard shortcuts

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