为什么在Go测试中使用-count=1会忽略缓存?

huangapple go评论65阅读模式
英文:

Why does -count=1 ignores caching in Go tests?

问题

我了解到,在Go测试中,为了避免使用缓存结果,可以在go test命令中使用-count=1标志,但为什么要这样做呢?

这是来自文档的说明:

> 禁用测试缓存的惯用方法是显式地使用-count=1

关于count标志的解释是:

-count n
    对每个测试、基准测试和模糊种子运行n次(默认值为1)。
    如果设置了-cpu,对于每个GOMAXPROCS值运行n次。
    示例总是运行一次。-count不适用于通过-fuzz匹配的模糊测试。

它没有提到任何关于缓存的内容,而默认值为1,但默认情况下不会忽略缓存的测试。

英文:

I understand that in order to avoid cached results in Go tests you can use the -count=1 flag in the go test command, but why?

This is from the docs:

> The idiomatic way to disable test caching explicitly is to use -count=1

The explanation for the count flag is:

-count n
    Run each test, benchmark, and fuzz seed n times (default 1).
    If -cpu is set, run n times for each GOMAXPROCS value.
    Examples are always run once. -count does not apply to
    fuzz tests matched by -fuzz.

It doesn't say anything about caching and the default value is 1, but skipping cached tests aren't ignored by default.

答案1

得分: 4

简单的答案是因为这是go工具的编写方式。

原因是:为了加快测试速度,测试输出被缓存起来。如果代码没有改变,测试输出也不应该改变。当然,这并不一定是真的,测试可能会从外部源读取信息,或者使用与时间和随机相关的数据,这些数据可能会在每次运行时发生变化。

当您使用-count标志请求多次测试运行时,显然意图是多次运行测试,没有逻辑只运行一次并显示n-1次相同的结果。因此,-count触发了省略缓存结果的操作。-count=1将只运行一次测试,省略之前缓存的输出。

英文:

The simple answer is because this is how the go tool is written.

The reasoning is: Test outputs are cached to speed up tests. If the code doesn't change, the test output shouldn't change either. Of course this is not necessarily true, tests may read info from external sources or may use time and random related data which could change from run to run.

When you request multiple test runs using the -count flag, obviously the intention is to run the tests multiple times, there's no logic running them just once and show n-1 times the same result. So -count triggers omitting the cached results. -count=1 will simply cause running the tests once, omitting previous cached outputs.

huangapple
  • 本文由 发表于 2022年8月21日 16:27:39
  • 转载请务必保留本文链接:https://go.coder-hub.com/73432741.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定