Categorygithub.com/tilinna/clock
modulepackage
1.1.0
Repository: https://github.com/tilinna/clock.git
Documentation: pkg.go.dev

# README

clock GoDoc Go Report Card

A Go (golang) library for mocking standard time, optionally also with context.Context.

Basic Usage

// Use clock.Realtime() in production
mock := clock.NewMock(time.Date(2018, 1, 1, 10, 0, 0, 0, time.UTC))
fmt.Println("Time is now", mock.Now())
timer := mock.NewTimer(15 * time.Second)
mock.Add(25 * time.Second)
fmt.Println("Time is now", mock.Now())
fmt.Println("Timeout was", <-timer.C)
// Output:
// Time is now 2018-01-01 10:00:00 +0000 UTC
// Time is now 2018-01-01 10:00:25 +0000 UTC
// Timeout was 2018-01-01 10:00:15 +0000 UTC

Context Usage

start := time.Date(2018, 1, 1, 10, 0, 0, 0, time.UTC)
mock := clock.NewMock(start)
fmt.Println("now:", mock.Now())
ctx, cfn := mock.DeadlineContext(context.Background(), start.Add(time.Hour))
defer cfn()
fmt.Println("err:", ctx.Err())
dl, _ := ctx.Deadline()
mock.Set(dl)
fmt.Println("now:", clock.Now(ctx))
<-ctx.Done()
fmt.Println("err:", ctx.Err())
// Output:
// now: 2018-01-01 10:00:00 +0000 UTC
// err: <nil>
// now: 2018-01-01 11:00:00 +0000 UTC
// err: context deadline exceeded

# Functions

After is a convenience wrapper for FromContext(ctx).After.
AfterFunc is a convenience wrapper for FromContext(ctx).AfterFunc.
Context returns a copy of parent in which the Clock is associated with.
DeadlineContext is a convenience wrapper for FromContext(ctx).DeadlineContext.
FromContext returns the Clock associated with the context, or Realtime().
NewMock returns a new Mock with current time set to now.
NewTicker is a convenience wrapper for FromContext(ctx).NewTicker.
NewTimer is a convenience wrapper for FromContext(ctx).NewTimer.
Now is a convenience wrapper for FromContext(ctx).Now.
Realtime returns the standard real-time Clock.
Since is a convenience wrapper for FromContext(ctx).Since.
Sleep is a convenience wrapper for FromContext(ctx).Sleep.
Tick is a convenience wrapper for FromContext(ctx).Tick.
TimeoutContext is a convenience wrapper for FromContext(ctx).TimeoutContext.
Until is a convenience wrapper for FromContext(ctx).Until.

# Structs

Mock implements a Clock that only moves with Add, AddNext and Set.
Ticker represents a time.Ticker.
Timer represents a time.Timer.

# Interfaces

Clock represents an interface to the functions in the standard time and context packages.