如何在Go中测量测试覆盖率

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

How to measure test coverage in Go

问题

有人成功地为Go单元测试生成代码覆盖率吗?我在网上找不到相关工具。

英文:

Has anyone succeeded in generating code coverage for Go unit tests? I can't find a tool for that on the web.

答案1

得分: 217

请注意,Go 1.2(2013年第四季度,rc1可用)现在将显示**测试覆盖率结果**:

> go test的一个重要新功能是它现在可以计算并显示测试覆盖率结果,需要借助一个新的、单独安装的“go tool cover”程序来实现
>
> cover工具是go.tools子存储库的一部分。可以通过运行以下命令来安装它:
>
> $ go get golang.org/x/tools/cmd/cover
>
> cover工具有两个功能。
>
> - 首先,当给go test传递-cover标志时,它会自动运行以重写包的源代码并插入插装语句。然后像往常一样编译和运行测试,并报告基本的覆盖率统计信息:
>
> $ go test -coverprofile fmtcoverage.html fmt
> ok fmt 0.060s coverage: 91.4% of statements
> $
>
> - 其次,为了获得更详细的报告,可以使用go test的不同标志创建一个覆盖率配置文件,然后使用“go tool cover”调用cover程序进行分析。

Frank Shearar 提到

> Go的最新版本(2013/09/19)使用:
>
> go test -coverprofile >
> 有关如何生成和分析覆盖率统计信息的详细信息可以通过运行以下命令找到:
>
> $ go help testflag
> $ go tool cover -help


Ivan Black评论中提到:

> go test -coverprofile cover.out然后
go tool cover -html=cover.out会在默认浏览器中打开cover.out
>
> 我甚至不想等待浏览器打开,所以我定义了这个别名:
>
> alias gc=grep -v -e " 1$" cover.out
>
> 我只需输入gc,就会得到一个所有尚未覆盖的行的列表(这里是一个以“1”结尾的coverage.out行)。


2022年更新,可能适用于Go 1.19

> ## 提案:扩展Go的代码覆盖测试以包括应用程序

> 虽然现有的基于“go test”的覆盖工作流将继续受到支持,但该提案是将覆盖率作为“go build”的新构建模式添加进来。
>
> 就像用户可以使用“go build -race”构建一个带有竞争检测器的可执行文件一样,可以使用“go build -cover”构建一个带有覆盖率检测的可执行文件。
>
> 支持合并在不同GOOS/GOARCH环境中生成的覆盖率配置文件。


2023年3月更新,Go 1.20:“Go集成测试的代码覆盖率”显示现在可以使用“go build -cover”构建带有覆盖率检测的程序,然后将这些插装的二进制文件输入到集成测试中,以扩展覆盖率测试的范围。

英文:

Note that Go 1.2 (Q4 2013, rc1 is available) will now display test coverage results:

> One major new feature of go test is that it can now compute and, with help from a new, separately installed "go tool cover" program, display test coverage results.
>
> The cover tool is part of the go.tools subrepository. It can be installed by running
>
> $ go get golang.org/x/tools/cmd/cover
>
> The cover tool does two things.
>
> - First, when "go test" is given the -cover flag, it is run automatically to rewrite the source for the package and insert instrumentation statements. The test is then compiled and run as usual, and basic coverage statistics are reported:
>
> $ go test -coverprofile fmtcoverage.html fmt
> ok fmt 0.060s coverage: 91.4% of statements
> $
>
> - Second, for more detailed reports, different flags to "go test" can create a coverage profile file, which the cover program, invoked with "go tool cover", can then analyze.

Frank Shearar mentions:

> The latest versions of Go (2013/09/19) use:
>
> go test -coverprofile <filename> <package name>
>
> Details on how to generate and analyze coverage statistics can be found by running the commands
>
> $ go help testflag
> $ go tool cover -help


Ivan Black mentions in the comments:

> go test -coverprofile cover.out and then
go tool cover -html=cover.out opens cover.out in your default browser
>
>I don't even want to wait for the browser to open, so I defined this alias:
>
> alias gc=grep -v -e " 1$" cover.out
>
> That I just type gc, and have a list of all the lines not yet covered (here: with a coverage.out line not ending with " 1").


Update 2022, possibly for Go 1.19

> ## proposal: extend Go's code coverage testing to include applications

> While the existing "go test" based coverage workflow will continue to be supported, the proposal is to add coverage as a new build mode for "go build".
>
> In the same way that users can build a race-detector instrumented executable using "go build -race", it will be possible to build a coverage-instrumented executable using "go build -cover".
>
> Merging coverage profiles produced in different GOOS/GOARCH environments will be supported.


Update March 2023, Go 1.20: "Code coverage for Go integration tests" shows that you can now build coverage-instrumented programs using “go build -cover”, then feed these instrumented binaries into an integration test to extend the scope of coverage testing.

答案2

得分: 65

Go提供了一些很棒的测试和覆盖率工具。虽然所有的Go工具都有很好的文档go tool cover -help,但我建议阅读官方Go博客上的覆盖率文章。它有很多例子,我强烈推荐!

我在我的~/.bash_profile中有这个函数(你可以将它粘贴到终端中尝试一下)。

cover () { 
    t="/tmp/go-cover.$$.tmp"
    go test -coverprofile=$t $@ && go tool cover -html=$t && unlink $t
}

然后只需cd到一个Go项目/包的文件夹中,然后输入cover
这将在浏览器中打开一个可视化工具,显示当前包中每个文件的已测试和未测试代码。非常有用的命令!我强烈推荐它用于查找哪些代码尚未100%测试!显示的结果是按文件显示的。从左上角的下拉菜单中,您可以查看所有文件的结果。

使用此命令,您还可以检查任何包的覆盖率,例如:

cover fmt

这个命令在终端中的输出将是:

ok  	fmt	0.031s	coverage: 91.9% of statements

除此之外,在浏览器中,您将看到这个工具以红色显示所有未被测试覆盖的代码行:

如何在Go中测量测试覆盖率

还可以将HTML覆盖率文件保存下来,而不是在浏览器中打开它。这在您的测试+覆盖率由像Jenkins这样的CI工具运行的情况下非常有用。这样,您可以从一个中央服务器提供覆盖率文件,整个团队都能够看到每个构建的覆盖率结果。

英文:

Go comes with awesome tool for testing and coverage. Although all Go tools are well documented go tool cover -help I would suggest reading The cover story article on the official Go blog. It has plenty of examples and I strongly recommend it!

I have this function in my ~/.bash_profile. (you can just paste it in the terminal to give it a try).

cover () { 
    t=&quot;/tmp/go-cover.$$.tmp&quot;
    go test -coverprofile=$t $@ &amp;&amp; go tool cover -html=$t &amp;&amp; unlink $t
}

Then just cd into a go project/package folder and type cover.
This opens a visual tool in browser which shows you the tested and untested code for each file in the current package. Very useful command! I strongly recommend it for finding what is not 100% tested yet! The shown results are per file. From a drop down in top-left you can see results for all files.

With this command you can also check the coverage of any package for example:

cover fmt

The output in terminal from this command would be:

ok  	fmt	0.031s	coverage: 91.9% of statements

In addition to that in your browser you will see this tool showing in red all lines of code which are not covered with tests:

如何在Go中测量测试覆盖率

It is also possible to just save the html coverage file instead of opening it in a browser. This is very useful in cases when your tests + coverage is run by CI tool like Jenkins. That way you can serve the coverage files from a central server and the whole team will be able to see the coverage results for each build.

答案3

得分: 64

除了上面的好答案之外,我发现以下三行是最简单的方法(包括所有包):

go test -v -coverprofile cover.out ./YOUR_CODE_FOLDER/...
go tool cover -html cover.out -o cover.html
open cover.html

请注意,在HTML文件中,您将找到一个下拉按钮,可以将您导向所有文件。

有关其他选项,请参阅go tool cover -help

英文:

In addition to the good answers above, I find these three lines to be the simplest way to get it (which includes all packages):

go test -v -coverprofile cover.out ./YOUR_CODE_FOLDER/...
go tool cover -html cover.out -o cover.html
open cover.html

Note that in the HTML file you will find a dropdown button that will direct you to all files.

See go tool cover -help for additional options.

答案4

得分: 31

只需运行

go test -cover

或者

go test -cover ./...

或者

go test -coverprofile=coverage.out ./... ;    go tool cover -func=coverage.out

或者检查源代码

go test -coverprofile=coverage.out ./... ;    go tool cover -html=coverage.out
英文:

Simply run

go test -cover

or

go test -cover ./...

or

go test -coverprofile=coverage.out ./... ;    go tool cover -func=coverage.out

or to check the source code

go test -coverprofile=coverage.out ./... ;    go tool cover -html=coverage.out

答案5

得分: 15

实际上...现在(2022年)在网上有这样一个工具,来自Nikolay Dubina的项目go-cover-treemap-web

https://go-cover-treemap.io/

没有上传任何内容(处理仍然在本地进行),但通过拖放您的覆盖文件,Web界面(使用Go WASM)将运行go-cover-treemap并显示:

如何在Go中测量测试覆盖率
<sup>(gocovergage for https://github.com/gohugoio/hugo)</sup>

英文:

> I can't find a tool for that on the web.

Actually... there is now (2022) such a tool on the web, from Nikolay Dubina's project go-cover-treemap-web:

https://go-cover-treemap.io/

Nothing it uploaded (the processing remains local), but by dragging/dropping your coverprofile, the Web UI (using Go WASM) will run go-cover-treemap and display:

如何在Go中测量测试覆盖率
<sup>(gocovergage for https://github.com/gohugoio/hugo)&lt;/sup>

答案6

得分: 12

覆盖率报告:

a) 运行所有测试并启用覆盖率 → go test ./... -coverprofile coverage.out

b) 获取每个函数以及整体覆盖率 → go tool cover -func coverage.out

c) 查看测试覆盖的行和未覆盖的行 → go tool cover -html=coverage.out -o coverage.html。在浏览器中打开生成的 coverage.html 文件并分析详细的覆盖信息。

英文:

Coverage Report:

a) Run all the tests and enable coverage --> go test ./... -coverprofile coverage.out

b) Get coverage for individual functions as well as overall coverage → go tool cover -func coverage.out

c) See the lines covered and the ones not covered by your tests → go tool cover -html=coverage.out -o coverage.html. Open the coverage.html file hereby generated in the browser and analyze the detailed coverage info.

答案7

得分: 11

已经内置在VSCode中

  1. Ctrl+Shift+P 打开命令面板
  2. Go: 切换测试覆盖率 ...

绿色部分已经经过测试,红色部分未经测试

如何在Go中测量测试覆盖率

英文:

Already built-in in VSCode

  1. Ctrl+Shift+P to Open Command Palette
  2. Go: Toggle Test Coverage ...

The Green part is tested and Red is not

如何在Go中测量测试覆盖率

答案8

得分: 5

这里是这里,一些文档这里

$ go tool
6a
6c
6g
6l
addr2line
api
cgo
cov
dist
ebnflint
fix
gotype
nm
objdump
pack
pprof
prof
vet
yacc
$ go tool cov -h
用法:cov [-lsv] [-g substring] [-m minlines] [6.out args...]
-g 指定感兴趣的函数或文件的模式
go tool cov: 退出状态 1
$

我没有使用过它,这就是我所知道的。

英文:

It's right here, some docs here.

$ go tool
6a
6c
6g
6l
addr2line
api
cgo
cov
dist
ebnflint
fix
gotype
nm
objdump
pack
pprof
prof
vet
yacc
$ go tool cov -h
usage: cov [-lsv] [-g substring] [-m minlines] [6.out args...]
-g specifies pattern of interesting functions or files
go tool cov: exit status 1
$

I haven't used it, this is all I know.

答案9

得分: 5

如果您喜欢在终端中直接查看函数的未覆盖行,我为此重新编写了覆盖工具。它可以在 https://github.com/gregoryv/uncover 上找到。

使用方法

go get -u github.com/gregoryv/uncover/...
go test -coverprofile /tmp/c.out
uncover /tmp/c.out

截图

如何在Go中测量测试覆盖率

英文:

If you like to see the uncovered lines by function directly in a terminal I rewrote the cover tool for this purpose. It's available at https://github.com/gregoryv/uncover.

Usage

go get -u github.com/gregoryv/uncover/...
go test -coverprofile /tmp/c.out
uncover /tmp/c.out

Screenshot

如何在Go中测量测试覆盖率

答案10

得分: 5

如果您正在使用VSCode,此功能已经内置支持(但默认情况下被禁用

只需打开“保存时测试”和“覆盖率报告”

https://github.com/microsoft/vscode-go/wiki/On-Save-features

它甚至会在编辑器中显示哪些行未被覆盖,非常方便。

英文:

If you are using VSCode this functionality is supported out the box ( But disabled by default )

Just turn on test on save + coverage reporting

https://github.com/microsoft/vscode-go/wiki/On-Save-features

It will even show in your editor which lines are not covered which is super handy.

答案11

得分: 2

f=cover.out
if [ -f $f ]; then
rm $f
fi
go test ./... -coverprofile $f &&
go tool cover -html $f &&
rm $f

英文:

Inspired by the help menus and other answers to this question, just run:

f=cover.out
if [ -f $f ]; then
  rm $f
fi
go test ./... -coverprofile $f &amp;&amp; \
go tool cover -html $f &amp;&amp; \
rm $f

答案12

得分: 2

如果你想在Windows中查找测试覆盖率,只需打开命令提示符并输入以下命令:

go test -coverprofile=coverage.out &amp;&amp; go tool cover -html=coverage.out

这非常简单且可靠地工作。

英文:

If you want to find test coverage in Windows, just go to the desired folder in command prompt and type the following command:

go test -coverprofile=coverage.out &amp;&amp; go tool cover -html=coverage.out

This is perfectly easy and works reliably.

答案13

得分: 1

一个快速简单的方法是使用内置的go覆盖工具:

> $ go test -coverprofile cp.out
// 以一行百分比的形式输出覆盖率

执行上述命令后,如果你希望可视化地查看代码覆盖率(例如已覆盖的语句和未覆盖的语句等),可以执行以下命令:

> $ go tool cover -html=cp.out

注意:你需要在希望查看覆盖率的文件夹中执行上述命令。

英文:

A quick and easy way is to use the coverage tool that comes with built-in go :

> $ go test -coverprofile cp.out
// Emits the coverage in one liner percentage wise

After you execute the above command, if you wish to visually see the code coverage (like covered statements and missed etc)

> $ go tool cover -html=cp.out

Note : You need to execute the above commands in the folder where you wish to see coverage

答案14

得分: 0

尝试使用**gaia-docker/base-go-build** Docker镜像。

这是一个包含构建和测试覆盖所需的所有内容的Docker镜像。
在Docker容器中运行测试覆盖会创建一个名为_.cover_的文件夹,其中包含项目的测试覆盖结果。

docker run --rm -v "$PWD":$PROJECT_PATH -w $PROJECT_PATH $BUILDER_IMAGE_NAME /go/script/coverage.sh

测试覆盖脚本在所有项目文件夹上运行,并在_.cover_文件夹中为每个文件夹生成junit和覆盖报告,以及所有项目测试的合并覆盖报告。

Codecov还提供了一个收集覆盖结果的脚本:多个文件

英文:

Try using gaia-docker/base-go-build Docker Image.

This is a Docker image that contains all you need in order to build and test coverage.
Running test coverage inside a Docker container creates .cover folder with test coverage results of your project.

docker run --rm -v &quot;$PWD&quot;:$PROJECT_PATH -w $PROJECT_PATH $BUILDER_IMAGE_NAME /go/script/coverage.sh

The test coverage script running on all projects' folders and generates, inside .cover folder junit and coverage reports for each folder, and a combine coverage report of all projects' tests.

Codecov also suggests a script that collect coverage results: multiple files

答案15

得分: -1

>Golang的测试覆盖率

go get github.com/axw/gocov/gocov go get -u gopkg.in/matm/v1/gocov-html

检查是否正确安装,并且您可以从终端访问

>运行测试用例

如果您运行测试用例,它将根据文件生成.json文件,您将在.html文件中获得代码覆盖率报告

gocov test &gt;your_Coverage_report.json

一旦您的测试用例完成,使用.json生成一个.html文件的报告

gocov-html your_Coverage_report.json &gt;your_Coverage_report.html

参考资料

Go语言的测试覆盖率工具

Go测试报告工具

>备选方法

Go原生测试覆盖率

go test -coverprofile=coverage.out
go tool cover -html=coverage.out
英文:

>Test Coverage for Golang


go get github.com/axw/gocov/gocov
go get -u gopkg.in/matm/v1/gocov-html

Check It is Installed Correctly And you have access from your Terminal

>Run the Test Case

If you run the test case it will Reder the .json File Based on the file you will get the Code Coverage Report in .html file

gocov test &gt;your_Coverage_report.json

Once Your Test case is done Generate a Report in .html File using .json

gocov-html your_Coverage_report.json &gt;your_Coverage_report.html

Reference

GoTest Coverage Tool for go lang

Go Test Report Tool

>Alternate Method

Go Native Test coverage

go test -coverprofile=coverage.out
go tool cover -html=coverage.out

huangapple
  • 本文由 发表于 2012年5月9日 20:59:15
  • 转载请务必保留本文链接:https://go.coder-hub.com/10516662.html
匿名

发表评论

匿名网友

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

确定