go test 禁用缓存

每当执行 go test 时,如果功能代码和测试代码没有变动,则在下一次执行时,会直接读取缓存中的测试结果,并通过 (cached) 进行标记。

要禁用测试缓存,可以通过 -count=1 标志来实现。

如下示例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# ~/test/hello-drone/go_demo [master ✗ (fe95bec)] [13:45:16]
➜ go test -v ./...
? go_demo [no test files]
=== RUN TestCreateUnixMillis
--- PASS: TestCreateUnixMillis (0.00s)
utils_test.go:7: 1561614325740
PASS
ok go_demo/utils 0.006s
# ~/test/hello-drone/go_demo [master ✗ (fe95bec)] [13:45:32]
➜ go test -v ./...
? go_demo [no test files]
=== RUN TestCreateUnixMillis
--- PASS: TestCreateUnixMillis (0.00s)
utils_test.go:7: 1561614325740
PASS
ok go_demo/utils (cached)
# ~/test/hello-drone/go_demo [master ✗ (fe95bec)] [13:45:38]
➜ go test -v ./...
? go_demo [no test files]
=== RUN TestCreateUnixMillis
--- PASS: TestCreateUnixMillis (0.00s)
utils_test.go:7: 1561614325740
PASS
ok go_demo/utils (cached)
# ~/test/hello-drone/go_demo [master ✗ (fe95bec)] [13:45:59]
➜ go test -v ./... -count=1
? go_demo [no test files]
=== RUN TestCreateUnixMillis
--- PASS: TestCreateUnixMillis (0.00s)
utils_test.go:7: 1561614494115
PASS
ok go_demo/utils 0.006s
# ~/test/hello-drone/go_demo [master ✗ (fe95bec)] [13:48:14]
➜ go test -v ./... -count=1
? go_demo [no test files]
=== RUN TestCreateUnixMillis
--- PASS: TestCreateUnixMillis (0.00s)
utils_test.go:7: 1561614508408
PASS
ok go_demo/utils 0.006s
# ~/test/hello-drone/go_demo [master ✗ (fe95bec)] [13:48:32]

关于 -count=1 的解释,可以通过命令 go help testflag 来查看:

1
2
3
4
5
When 'go test' runs in package list mode, 'go test' caches successful
package test results to avoid unnecessary repeated running of tests. To
disable test caching, use any test flag or argument other than the
cacheable flags. The idiomatic way to disable test caching explicitly
is to use -count=1.

总结

Go 1.11 之前,通过 GOCACHE=off 的方式来禁用测试缓存:GOCACHE=off go test ./...

Go 1.11 之后,通过 -count=1 的方式来禁用测试缓存:go test -count=1 ./...

相关参考

坚持原创技术分享,您的支持将鼓励我继续创作!
如有疑问或需要技术讨论,请留言或发邮件到 service@itfanr.cc