在集成测试中如何进行 Golang 代码覆盖率测试?

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

golang code coverage in integration tests?

问题

似乎"go tool cover -var=foo"的目的是生成可以在集成测试环境中部署的插装代码。有人在使用这个功能来实现这个目的吗?如果是这样,是否有一种常规的方法来定期输出计数器?在所有感兴趣的文件中几乎同时进行这个操作可能是棘手的。即使如此,一些偏差(如果使用-mode=count)是不可避免的。

英文:

It seems the point of "go tool cover -var=foo" may be to generate instrumented code that can be deployed in an integration test harness. Is anyone using this feature for that purpose? If so, is there a conventional way to dump the counters periodically? It seems the tricky part would be doing this across all files of interest with near simultaneity. Even then, some skew (if using -mode=count) would be unavoidable.

答案1

得分: 9

我们使用这个方法来收集来自各种测试的代码覆盖率,以获得测试中的单一代码覆盖率数字,并查看未覆盖的代码路径。

  • 模块测试
  • 集成测试
  • UI 测试
  • API 测试
  • 单元测试

实现这个目标的方法是:

  • 构建一个启用了覆盖率的仪器化二进制文件(app.debug)。下面的命令将生成一个启用了覆盖率仪器化的 app.debug 文件。

      $ go test -c -covermode=atomic -coverpkg="pkg/path/..." -o app.debug
    
  • 在测试中使用这个 app.debug 文件而不是你的应用程序,并对其运行测试。我们的应用程序是一个 HTTP 服务器,但对大多数应用程序来说,这个方法都适用。每个测试都会生成一个单独的 cov 文件,稍后需要将它们合并。

      $ ./app.debug -test.coverprofile=functest.cov -- app.params
    
  • 合并所有的测试 cov 文件以获得一个单一的 cov 文件。你可以使用 gocovmerge 来完成这个操作。

      $ find $COVERAGE_DIR -name *.cov | xargs gocovmerge > final.cov
    

最终,你将得到一个覆盖率文件,它能够完整地展示各种覆盖率的代码情况。

英文:

We use this to collect code coverage from our various tests to get a single code coverage number across the tests and to see the uncovered code paths

  • Module tests
  • Integration tests
  • UI tests
  • API tests
  • unit tests

The way to achieve this is

  • Build an instrumented binary (app.debug) with coverage enables. The below command generates an app.debug with coverage instrumentation enabled

      $ go test -c -covermode=atomic -coverpkg="pkg/path/..." -o app.debug
    
  • Use this app.debug instead of your app in the tests and run tests against it. Ours is an HTTP server but this should work for most applications. Each test generates a seperate cov file which later needs to be merged.

      $ ./app.debug -test.coverprofile=functest.cov -- app.params
    
  • Merge all the test cov files to get a single cov file .For this, you can use gocovmerge

      $ find $COVERAGE_DIR -name *.cov | xargs gocovmerge > final.cov
    

And you have finally a coverage file which gives you complete picture of code coverage from all sorts of coverage.

huangapple
  • 本文由 发表于 2015年1月22日 12:33:23
  • 转载请务必保留本文链接:https://go.coder-hub.com/28081348.html
匿名

发表评论

匿名网友

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

确定