使用jonboulle/clockwork包mock时间

55 阅读2分钟

Clockwork 是一个 Go 语言编写的用于处理时间相关操作的库。

其提供了对时间的模拟和操作功能,适用于需要在测试中控制时间流逝的场景。

下面是一个简单的示例,演示如何使用 Clockwork 进行时间模拟:

在线代码执行

package main

import (
	"fmt"
	"time"

	"github.com/jonboulle/clockwork"
)

func main() {
	// 创建 Clockwork 实例
	fakeClock := clockwork.NewFakeClock()

	// 使用模拟时间
	now := fakeClock.Now()
	fmt.Println("Current time:", now)

	// 模拟时间流逝(模拟过了两个小时)
	fakeClock.Advance(2 * time.Hour)

	// 获取更新后的时间
	updatedTime := fakeClock.Now()
	fmt.Println("Updated time:", updatedTime)

	// 比较updatedTime是否在now之后
	isAfter := updatedTime.After(now)
	fmt.Println("Is updated time after current time:", isAfter)
}

运行以上代码,输出如下:

Current time: 2023-05-19 18:37:30.167661 +0800 CST m=+0.000150751
Updated time: 2023-05-19 20:37:30.167661 +0800 CST m=+7200.000150751
Is updated time after current time: true

上面示例创建了一个 FakeClock 实例,使用clockwork来模拟时间。通过调用 Advance 方法,模拟了时间流逝,然后比较了更新后的时间与当前时间的关系(在测试中,这种时间模拟的能力是非常有用的,可以方便地控制测试用例中的时间行为)。

综上,可以在测试中更轻松地控制时间相关的行为,如定时任务、超时等(时间模拟 ),可以有效解决测试中时间相关问题, 很好地控制时间,隔离代码中的时间依赖,实现可重复的测试。

还提供了方便的时间操作方法,如增加、减少、比较等(方便的时间操作 )。


在很多项目中都有使用,如

kubectl:

pkg/cmd/apply/patcher.go#L70

pkg/cmd/diff/diff.go#L400

etcd:

etcd/server/etcdserver/api/v3compactor/compactor.go

etcd/server/etcdserver/api/v3compactor/revision_test.go