How to ignore Generated files from Go test coverage

I have a generated file in my package with DO NOT EDIT on top. I am running tests for my package with go test -coverprofile=cover.out <package> . This creates coverage profile and shows total coverage percentage. But it also includes generated files while calculating the coverage. Is there a way to ignore generated files in coverage calculation?


Most Go tools operate on packages, because a package itself forms a unit that may be useful in its entirety. Excluding files from a package could easily "break" the package: the excluded file may contain (crucial) package initialization code or may even cause the remaining package files fail to compile.

go test is no exception: it also operates on packages. There is no first-hand support to exclude files from a package.

If your package may be compiled and tested without the generated file, you may opt to generate the file into a different package, and then it won't be included in your package's (coverage) test naturally.

Another way to handle this would be to still generate it in the same package / folder, and use special build tags in the generated files, which you may exclude when running the coverage test. You can read more about build tags here: Build Constraints, and here: What is the right approach to encapsulate platform specific code in Go?

If the generated file is needed to compile / test the package, then you still have an option: use an internal package for the generated file. Internal packages are only available to the package tree rooted at the internal folder, which means you may export any identifiers in an internal package, the compiler ensures they won't be used by "unintended" parties. You can read more about internal packages here: Can I develop a go package in multiple source directories?

Also consider the option to write or generate test for the generated code, which may be good practice anyway, so you wouldn't have to use tricks to exclude them from coverage tests.


You could strip the generated code from the cover profiles:

go test . -coverprofile cover.out.tmp
cat cover.out.tmp | grep -v "_generated.go" > cover.out
tool cover -func cover.out

Depending on the used tools this can be implemented easily in the pipeline/make.

链接地址: http://www.djcxy.com/p/41570.html

上一篇: 使ViewPager + WebView以连续方式垂直滑动

下一篇: 如何忽略来自Go测试覆盖的生成文件