如何忽略 Go 测试覆盖率中生成的文件 [英] How to ignore generated files from Go test coverage

查看:31
本文介绍了如何忽略 Go 测试覆盖率中生成的文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的包中有一个生成的文件,顶部有 DO NOT EDIT.我正在使用 go test -coverprofile=cover.out <package> 为我的包运行测试.这将创建覆盖率配置文件并显示总覆盖率百分比.但它也包括在计算覆盖率时生成的文件.有没有办法在覆盖率计算中忽略生成的文件?

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?

推荐答案

大多数 Go 工具对包进行操作,因为包本身形成了一个单元,它可能在整体上很有用.从包中排除文件很容易破坏"包:被排除的文件可能包含(关键)包初始化代码,甚至可能导致剩余的包文件无法编译.

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 也不例外:它也对包进行操作.没有第一手支持从包中排除文件.

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.

另一种处理方法是仍然在同一个包/文件夹中生成它,并在生成的文件中使用特殊的构建标记,您可以在运行覆盖测试时排除这些标记.您可以在此处阅读有关构建标记的更多信息:构建约束,以及此处:什么是正确的方法在 Go 中封装特定于平台的代码?

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?

如果需要生成的文件来编译/测试包,那么您还有一个选择:对生成的文件使用内部包.内部包仅可用于以 internal 文件夹为根的包树,这意味着您可以导出内部包中的任何标识符,编译器确保它们不会被非预期"方使用.您可以在此处阅读有关内部包的更多信息:我可以在多个源目录中开发一个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.

这篇关于如何忽略 Go 测试覆盖率中生成的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆