jonboulle/clockwork
GitHub: jonboulle/clockwork
clockwork 为 Go 提供了一个可替换的时钟接口,让涉及时间的代码在单元测试中可以通过 FakeClock 精确控制时间流逝,无需真实等待。
Stars: 726 | Forks: 63
# clockwork
[](https://github.com/avelino/awesome-go#utilities)
[](https://github.com/jonboulle/clockwork/actions?query=workflow%3ACI)
[](https://goreportcard.com/report/github.com/jonboulle/clockwork)

[](https://pkg.go.dev/mod/github.com/jonboulle/clockwork)
**一个用于 Go 的简单模拟时钟。**
## 用法
将 `time` 包的使用替换为 `clockwork.Clock` 接口。
例如,不要直接使用 `time.Sleep`:
```
func myFunc() {
time.Sleep(3 * time.Second)
doSomething()
}
```
而是注入一个 clock,并使用其 `Sleep` 方法:
```
func myFunc(clock clockwork.Clock) {
clock.Sleep(3 * time.Second)
doSomething()
}
```
现在你可以轻松地使用 `FakeClock` 来测试 `myFunc`:
```
func TestMyFunc(t *testing.T) {
ctx := context.Background()
c := clockwork.NewFakeClock()
// Start our sleepy function
var wg sync.WaitGroup
wg.Add(1)
go func() {
myFunc(c)
wg.Done()
}()
// Ensure we wait until myFunc is waiting on the clock.
// Use a context to avoid blocking forever if something
// goes wrong.
ctx, cancel := context.WithTimeout(ctx, 10*time.Second)
defer cancel()
c.BlockUntilContext(ctx, 1)
assertState()
// Advance the FakeClock forward in time
c.Advance(3 * time.Second)
// Wait until the function completes
wg.Wait()
assertState()
}
```
在生产构建中,只需注入真实的时钟即可:
```
myFunc(clockwork.NewRealClock())
```
有关完整示例,请参见 [example_test.go](example_test.go)。
# 鸣谢
clockwork 的灵感来源于 @wickman 的 [threaded fake clock](https://gist.github.com/wickman/3840816) 以及 [Golang playground](https://blog.golang.org/playground#TOC_3.1.)
## 许可证
Apache License, Version 2.0。请查看 [许可证文件](LICENSE) 了解更多信息。
标签:EVTX分析, Golang, Mock, 安全编程, 开发组件库, 日志审计, 时间模拟, 测试工具