πŸ•“ Time utility with lovely mocking support
ΠŸΠ΅Ρ€Π΅ΠΉΡ‚ΠΈ ΠΊ Ρ„Π°ΠΉΠ»Ρƒ
microsoft-github-policy-service[bot] 4933054921
Microsoft mandatory file (#25)
Co-authored-by: microsoft-github-policy-service[bot] <77245923+microsoft-github-policy-service[bot]@users.noreply.github.com>
2022-09-22 09:25:03 -07:00
example feat: add `Since(t Time) Duration` shorthand (#12) 2017-09-01 08:02:40 -07:00
.gitignore fix(ticker): deadlock on Close() 2017-08-01 12:46:03 -07:00
.travis.yml chore(travis): Update Go versions in .travis.yml (#9) 2017-08-14 11:59:42 -07:00
LICENSE Update license 2016-07-19 15:32:16 -07:00
SECURITY.md Microsoft mandatory file (#25) 2022-09-22 09:25:03 -07:00
clock.go docs: fix typos and style to match godoc conventions 2018-10-04 08:21:42 -07:00
default.go docs: fix typos and style to match godoc conventions 2018-10-04 08:21:42 -07:00
go.mod feat: add go.mod file (#16) 2020-07-13 11:19:18 -07:00
go.sum feat: add go.mod file (#16) 2020-07-13 11:19:18 -07:00
mock.go test: add a few tests and small refactor 2018-10-06 10:17:04 -07:00
mock_test.go test: add a few tests and small refactor 2018-10-06 10:17:04 -07:00
readme.md fix markdown bug (#22) 2021-03-21 09:15:42 -07:00
ticker.go docs: fix typos and style to match godoc conventions 2018-10-04 08:21:42 -07:00
timer.go fix race in NewTimer() 2019-01-31 08:52:14 -08:00

readme.md

clock GoDoc Build Status

Time utility with lovely mocking support.

This is essentially a replacement for the time package which allows you to seamlessly swap in mock times, timers, and tickers. See the godocs (link above) for more detailed usage.

Example

hello.go

package main

import (
    "fmt"
    "github.com/mixer/clock"
)

func main() {
    fmt.Printf("the time is %s", displayer{clock.C}.formatted())
}

type displayer struct {
    c clock.Clock
}

func (d displayer) formatted() string {
    now := d.c.Now()
    return fmt.Sprintf("%d:%d:%d", now.Hour(), now.Minute(), now.Second())
}

hello_test.go

package main

import (
    "testing"
    "time"

    "github.com/mixer/clock"
    "github.com/stretchr/testify/assert"
)

func TestDisplaysCorrectly(t *testing.T) {
    date, _ := time.Parse(time.UnixDate, "Sat Mar  7 11:12:39 PST 2015")
    c := clock.NewMockClock(date)
    d := displayer{c}

    assert.Equal(t, "11:12:39", d.formatted())
    c.AddTime(42 * time.Second)
    assert.Equal(t, "11:13:21", d.formatted())
}

API & Compatibility

The API provided by this package and the mock version is nearly identical to that of the time package, with two notable differences:

  • The channel for Ticker and Timer instances is accessed via the .Chan() method, rather than reading the .C property. This allows the structures to be swapped out for their mock variants.
  • The mock Ticker never skips ticks when time advances. This allows you to call .AddTime/.SetTime on the mock clock without having to advance to each "ticked" time.