Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/microsoft/clock
:clock4: Time utility with lovely mocking support
https://github.com/microsoft/clock
Last synced: 11 days ago
JSON representation
:clock4: Time utility with lovely mocking support
- Host: GitHub
- URL: https://github.com/microsoft/clock
- Owner: microsoft
- License: mit
- Archived: true
- Created: 2015-12-30T22:11:09.000Z (almost 9 years ago)
- Default Branch: master
- Last Pushed: 2022-10-10T21:28:40.000Z (about 2 years ago)
- Last Synced: 2024-08-02T06:25:06.201Z (3 months ago)
- Language: Go
- Size: 28.3 KB
- Stars: 76
- Watchers: 40
- Forks: 17
- Open Issues: 2
-
Metadata Files:
- Readme: readme.md
- License: LICENSE
- Security: SECURITY.md
Awesome Lists containing this project
README
# clock [![GoDoc](https://godoc.org/github.com/mixer/clock?status.svg)](https://godoc.org/github.com/mixer/clock) [![Build Status](https://travis-ci.org/mixer/clock.svg)](https://travis-ci.org/mixer/clock)
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**
```go
package mainimport (
"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**
```go
package mainimport (
"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.