我如何在 Go 中编写使用 -short 标志的测试,它可以与 -benchmark 标志结合使用吗?

How do I write test in Go that make use of the -short flag and can it be combined with the -benchmark flag?

如何使用 go test -short 中给出的 -short 标志?

是否可以组合 -short-benchmark 标志?

我对 Go 语言还很陌生,但我正在努力使自己适应它的一些常见做法。这部分是为了尝试确保我的代码不仅以 go test 系统工作的方式添加了单元测试,而且 go test -benchmark 也以有用的方式运行。

目前我有一个基准测试,其中包括一系列基于不同大小的输入数据的子测试。 运行 15 种排列需要很长时间,所以最好提供缩短测试时间的选项。

我计划编写的下一组测试可能包括一系列数据输入示例。我希望 运行 中的一个可以作为短期测试的健全性检查,但是可以选择 运行 几个较长(或正常)的测试 运行s 会很好.

当我查看 the GoLang documentation for the testing flags 时它说 "Tell long-running tests to shorten their run time." 这听起来像我想要的,但我不知道如何在测试代码中选择这个标志。

How do I make use of the -short flag given in go test -short?

在命令行上使用短标记会导致 testing.Short() 函数变为 return true。您可以使用它来添加测试用例或跳过它们:

if testing.Short() == false {
    // Extra test code here
}

以上可能有点不寻常,可能更常见的是:

func TestThatIsLong(t *testing.T) {
    if testing.Short() {
        t.Skip()
    }
}

请务必为您的 -short 运行 准备足够的测试用例,以至少进行最低限度的检查。有些人建议使用 -short 运行 进行主要的持续集成和预提交检查,同时为计划的每日或每周构建或合并保留较长的测试 运行。

Documents section of The Go Programming Language site mentions how to write test code briefly but the bulk of information about the topic is in the Package Documentation for the Go Testing Package。对于大多数主题,大部分文档都可以在包中找到,而不是单独的。这可能与 class 和包文档通常很差的其他语言有很大不同。


Is it possible to combine the -short and -benchmark flags?

这是可能的,因为 testing.Short() 是全局范围的。但是,建议基准测试不要大量使用 -short 标志来控制它们的行为。 运行 进行基准测试的人更常见的是更改每个基准测试用例允许的 -benchtime

默认情况下,基准时间设置为一秒。如果你有 60 个基准测试用例,那么完成 运行(设置时间 + 执行时间)至少需要六十秒。如果 benchtime 设置为 less:

go test -benchmem -benchtime 0.5s -bench=. <package_names>

整体执行时间会按比例下降。

go command documentation's Testing Flags section 中描述了各种测试 clag(不是未提及 benchtime 的包文档)。您不需要在基准代码中做任何不同的事情来使基准时间有效,只需使用标准 for i := 0; i < b.N; i++ {,框架将根据需要调整 N 的值。

虽然不推荐,但我在基准测试中使用 -short 来减少测试用例的数量,当改变函数的输入以给出其 Big O notation 的指示时。对于所有基准 运行s(-short 和 normal),我为输入保留了一个具有代表性的数据大小以跟踪长期趋势。对于较长的 运行s,我包含了几个小型和大型数据集,以允许对函数资源需求进行近似。对于单元测试用例,我选择 运行 -short 版本始终在 CI 中,而较长的版本则按计划进行。


无论您对 Go 有什么问题,强烈建议您尝试通读 https://golang.org/doc/ and relevant https://golang.org/pkg/ 文档。最有用的文档通常在包文档中。