golang 生成功能测试的代码覆盖率

标签 go code-coverage functional-testing

我有一个 go webservices(一个 REST Api),我们对其进行了单元测试,并且 go cover 工作正常。

现在我们有一个用 python 编写的测试套件,它启动服务器实例、运行测试、停止服务器。

我想知道是否有一些工具允许我使用特定标志运行我的服务器二进制文件,以便在最后打印由我的“黑盒”测试执行的测试的覆盖范围?

谢谢。

最佳答案

基于 this post这是我所做的:

  1. 使用以下内容创建了一个 main_test.go:

    package main
    
    // code based on technique explained here:
    // https://www.elastic.co/blog/code-coverage-for-your-golang-system-tests
    // you can look there if you want to see how not to execute this test
    // when running unit test etc.
    
    // This file is mandatory as otherwise the packetbeat.test binary is not generated correctly.
    
    import (
        "testing"
    )
    
    // Test started when the test binary is started. Only calls main.
    func TestSystem(t *testing.T) {
        main()
    }
    
  2. 因为它是一个网络服务(因此处于无限循环中),我需要一种在 SIGTERM 上正常退出的方法(不会被视为失败),所以我使用了包 go get gopkg .in/tylerb/graceful.v1 并替换(我使用 go-restful)在 main.go 行

        -       log.Fatal(http.ListenAndServe(":"+port, nil))
        +       graceful.Run(":"+port, 10*time.Second, nil)
    
  3. 然后我会像这样运行测试

    • go test -c -covermode=count -coverpkg ./... -o foo.test
    • ./foo.test -test.coverprofile coverage.cov & echo $! >/tmp/test.pid
    • 运行我的测试套件
    • kill "$(cat/tmp/test.pid)"

关于golang 生成功能测试的代码覆盖率,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34837542/

相关文章:

go - Go 上是否存在类似于 C++ 中的宏之类的东西,比如 #ifdef 这样我就可以根据标志选择要构建的内容?

html - Go: template.ParseFiles() 不适用于 {{.active}} 但适用于 {{printf "%s".active}}

android - Emma 不生成 coverage.ec

python - 使 py.test、coverage 和 tox 一起工作 : __init__. py 在测试文件夹中?

ant - Cobertura 与 Ant 脚本 : xml/html coverage report always show 0% coverage everywhere

go - 何时使用 var 或 := in Go?

go - 如何在 Golang 中生成唯一的随机字母数字标记?

browser - 使用Casper.js,是否可以接受浏览器权限提示?

java - 如何在 Spring Boot 应用程序中模拟外部依赖关系?

testing - 如何使用intern js调试功能测试