【问题标题】:How to get all packages' code coverage together in Go?如何在 Go 中获得所有包的代码覆盖率?
【发布时间】:2016-01-31 09:49:05
【问题描述】:

我有一个由几个包组成的库。运行测试时,我使用“-cover”标志并分别显示每个包的覆盖率信息。如下所示:

--- PASS: TestSampleTestSuite (0.00s)
PASS
coverage: 28.7% of statements
ok      github.com/path/to/package1 13.021s
?       github.com/path/to/package2 [no test files]

=== RUN   TestAbc
--- PASS: TestAbc (0.43s)
PASS
coverage: 27.7% of statements

有没有什么方法可以轻松获得完整的覆盖率概览,以便更好地了解整个项目的覆盖率?

更新:这是我正在使用的 go test 命令

go test ./... -v -short -p 1 -cover

【问题讨论】:

  • 您能否编辑您的帖子以在您的参数中包含go test 命令?
  • 好的,完成!如果有帮助,请告诉我。

标签: unit-testing go code-coverage


【解决方案1】:

编辑:自从我写下这个答案以来,情况发生了变化。请参阅 Go 1.10 的发行说明:https://golang.org/doc/go1.10#test

go test -coverpkg 标志现在将其参数解释为 以逗号分隔的模式列表,以匹配 每个测试,而不是作为重新加载的包列表。例如,去 test -coverpkg=all 现在是一种有意义的方式来运行覆盖率测试 为测试包及其所有依赖项启用。还有,去 运行多个时现在支持 test -coverprofile 选项 测试。

您现在可以运行

go test -v -coverpkg=./... -coverprofile=profile.cov ./...
go tool cover -func profile.cov

旧答案

这是从https://github.com/h12w/gosweep 中提取的 bash 脚本:

#!/bin/bash
set -e

echo 'mode: count' > profile.cov

for dir in $(find . -maxdepth 10 -not -path './.git*' -not -path '*/_*' -type d);
do
if ls $dir/*.go &> /dev/null; then
    go test -short -covermode=count -coverprofile=$dir/profile.tmp $dir
    if [ -f $dir/profile.tmp ]
    then
        cat $dir/profile.tmp | tail -n +2 >> profile.cov
        rm $dir/profile.tmp
    fi
fi
done

go tool cover -func profile.cov

【讨论】:

  • 好吧,它仍然显示每个包的覆盖信息,这是我从给定命令中获得的。任何调整以获得整体覆盖信息?
  • 我也得到了“坏模式行”。我必须在开头添加行 echo "mode: count" > profile.cov
  • 我是否认为这只会覆盖那些有一些测试的文件?此外,我必须添加 -not -path './vendor/*' 以忽略供应商的软件包。
  • @danielcooperxyz 是正确的。没有测试的包将生成一个包含mode: count 的单行配置文件。 tail 命令将删除此行并且不向 profile.cov 附加任何内容。这会阻止go tool cover -func profile.cov 准确计算总覆盖率。值得一提的是,go test -coverprofile=profile.cov ./... 在功能上与该脚本的大部分内容相同,并且存在同样的不准确性。
  • @rubystallion 添加了一个关于如何使用它们的示例
猜你喜欢
  • 2014-06-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-01-29
  • 2021-01-24
  • 1970-01-01
  • 2016-02-25
  • 2013-09-12
相关资源
最近更新 更多